qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
285,775
|
<p>One of my columns is called <code>from</code>. I can't change the name because I didn't make it.
Am I allowed to do something like <code>SELECT from FROM TableName</code> or is there a special syntax to avoid the SQL Server being confused?</p>
|
[
{
"answer_id": 285777,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 10,
"selected": true,
"text": "from select [from] from table;\n select table.[from] from table;\n"
},
{
"answer_id": 285783,
"author": "John Baughman",
"author_id": 26923,
"author_profile": "https://Stackoverflow.com/users/26923",
"pm_score": 3,
"selected": false,
"text": "select [select]\nfrom [table]\n"
},
{
"answer_id": 285795,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 5,
"selected": false,
"text": "SELECT [from] AS TransferFrom -- Or something else more suitable\nFROM TableName\n"
},
{
"answer_id": 293009,
"author": "some",
"author_id": 36866,
"author_profile": "https://Stackoverflow.com/users/36866",
"pm_score": 5,
"selected": false,
"text": "select \"from\" from \"table\";\n"
},
{
"answer_id": 8871217,
"author": "user247487",
"author_id": 247487,
"author_profile": "https://Stackoverflow.com/users/247487",
"pm_score": 1,
"selected": false,
"text": "Select [from] from < ur_tablename>\n Declare @temp_table table(temp_from varchar(max))\n\nInsert into @temp_table\nSelect * from your_tablename\n"
},
{
"answer_id": 12340258,
"author": "preyingrazor",
"author_id": 1658315,
"author_profile": "https://Stackoverflow.com/users/1658315",
"pm_score": 2,
"selected": false,
"text": "type type CREATE TABLE alpha1\nAS\n(\nSEL\nproduct1\ntype_of_product AS \"type\"\nFROM beta1\n) WITH DATA\nPRIMARY INDEX (product1)\n\n--type is a SQL reserved keyword\n\nTYPE\n\n--see? now to retrieve the column you would use:\n\nSEL \"type\" FROM alpha1\n"
},
{
"answer_id": 12354437,
"author": "Rudolf Real",
"author_id": 1242821,
"author_profile": "https://Stackoverflow.com/users/1242821",
"pm_score": 2,
"selected": false,
"text": "UPDATE `survey`\nSET survey.values='yes,no'\nWHERE (question='Did you agree?')\n"
},
{
"answer_id": 19891609,
"author": "Muneeb Hassan",
"author_id": 775393,
"author_profile": "https://Stackoverflow.com/users/775393",
"pm_score": 2,
"selected": false,
"text": "string query= \"Select [Name],[Email] from Person\";\n"
},
{
"answer_id": 24532098,
"author": "user3797709",
"author_id": 3797709,
"author_profile": "https://Stackoverflow.com/users/3797709",
"pm_score": 2,
"selected": false,
"text": "SELECT DISTINCT table.from AS a FROM table\n"
},
{
"answer_id": 29441254,
"author": "Sunil Kapil",
"author_id": 1801075,
"author_profile": "https://Stackoverflow.com/users/1801075",
"pm_score": 5,
"selected": false,
"text": "SELECT TableName.from FROM TableName"
},
{
"answer_id": 36354231,
"author": "Kun Wu",
"author_id": 894557,
"author_profile": "https://Stackoverflow.com/users/894557",
"pm_score": 3,
"selected": false,
"text": "select `from` from table;\n"
},
{
"answer_id": 44162398,
"author": "cacti5",
"author_id": 5839007,
"author_profile": "https://Stackoverflow.com/users/5839007",
"pm_score": 1,
"selected": false,
"text": "select [from] from <table>\n"
},
{
"answer_id": 71177522,
"author": "Nishant Shah",
"author_id": 1256210,
"author_profile": "https://Stackoverflow.com/users/1256210",
"pm_score": 1,
"selected": false,
"text": "Select * from user u where u.from=\"US\"\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25645/"
] |
285,782
|
<p>I have been using git for several months in a project developed only by myself. I have a local repository and push it regularly to github for backup purposes.</p>
<p>I want to add another developer to this project, however I will have the responsibility of integrating the whole project.</p>
<p>What is the recommended workflow? </p>
<p>Do we need a private and a public repository for each developer?</p>
<p>If the github repository is the main one, does the other developer have to clone this repository or the repository in my computer?</p>
<p>Should he have the right to push in my repository or should I pull from his repository?</p>
|
[
{
"answer_id": 285803,
"author": "Chris Vest",
"author_id": 13251,
"author_profile": "https://Stackoverflow.com/users/13251",
"pm_score": 3,
"selected": false,
"text": "git format-patch"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14755/"
] |
285,790
|
<pre><code>while (xxx) {
timeout.tv_sec=TIMEOUT;
timeout.tv_usec=0;
FD_ZERO(&set);
FD_SET(sd,&set);
switch (select(FD_SETSIZE,&set,NULL,NULL,&timeout))
xxxxx
}
</code></pre>
<p>works fine, however</p>
<pre><code>FD_ZERO(&set);
FD_SET(sd,&set);
while (xxx) {
timeout.tv_sec=TIMEOUT;
timeout.tv_usec=0;
switch (select(FD_SETSIZE,&set,NULL,NULL,&timeout))
xxxxx
}
</code></pre>
<p>doesn't. It works the first time around, but the next time it runs through the while loop it gets a timeout even if the sd socket receives data. It seems to me to be a waste of resources to have to empty and fill set every time.</p>
<p>Anybody have a good explanation why this is, and even better, perhaps a suggestion how to avoid it?</p>
|
[
{
"answer_id": 286231,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 5,
"selected": true,
"text": "switch (select((sd + 1),&set,NULL,NULL,&timeout))\n FD_SET(sd,&set);\nif (sd > max) max = sd;\n... repeat many times...\n\nswitch (select((max + 1),&set,NULL,NULL,&timeout))\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37169/"
] |
285,793
|
<p>Eclipse issues warnings when a <code>serialVersionUID</code> is missing. </p>
<blockquote>
<p>The serializable class Foo does not declare a static final
serialVersionUID field of type long</p>
</blockquote>
<p>What is <code>serialVersionUID</code> and why is it important? Please show an example where missing <code>serialVersionUID</code> will cause a problem.</p>
|
[
{
"answer_id": 285809,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 12,
"selected": true,
"text": "java.io.Serializable serialVersionUID serialVersionUID InvalidClassException serialVersionUID serialVersionUID long ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;\n serialVersionUID serialVersionUID serialVersionUID serialVersionUID InvalidClassExceptions serialVersionUID serialVersionUID serialVersionUID serialVersionUID"
},
{
"answer_id": 285827,
"author": "Scott Bale",
"author_id": 2495576,
"author_profile": "https://Stackoverflow.com/users/2495576",
"pm_score": 8,
"selected": false,
"text": "serialVersionUID serialVersionUID writeObject readObject Serializable"
},
{
"answer_id": 286254,
"author": "MetroidFan2002",
"author_id": 8026,
"author_profile": "https://Stackoverflow.com/users/8026",
"pm_score": 9,
"selected": false,
"text": "HTTPSession de-serializing serialVersionUID SerialVersionUID"
},
{
"answer_id": 4881563,
"author": "Paŭlo Ebermann",
"author_id": 600500,
"author_profile": "https://Stackoverflow.com/users/600500",
"pm_score": 5,
"selected": false,
"text": "implements Serializable public class MyExample extends ArrayList<String> {\n\n public MyExample() {\n super();\n }\n ...\n}\n public class MyExample {\n private List<String> myList;\n\n public MyExample() {\n this.myList = new ArrayList<String>();\n }\n ...\n}\n myList.foo() this.foo() super.foo()"
},
{
"answer_id": 12702699,
"author": "Alexander Torstling",
"author_id": 83741,
"author_profile": "https://Stackoverflow.com/users/83741",
"pm_score": 7,
"selected": false,
"text": "serialVersionUID serialVersionUID in.defaultReadObject() serialVersionUID serialVersionUID serialVersionUID in.defaultReadObject() serialVersionUID"
},
{
"answer_id": 15388086,
"author": "Mukti",
"author_id": 2165875,
"author_profile": "https://Stackoverflow.com/users/2165875",
"pm_score": 4,
"selected": false,
"text": "Serializable serialVersionUID @SuppressWarnings(\"serial\")\n"
},
{
"answer_id": 15861472,
"author": "Rupesh",
"author_id": 1270989,
"author_profile": "https://Stackoverflow.com/users/1270989",
"pm_score": 6,
"selected": false,
"text": "Serial Version ID Car Car Car java.io.InvalidClassException serialVersionUID public class Car {\n static final long serialVersionUID = 1L; //assign a long value\n}\n"
},
{
"answer_id": 16656980,
"author": "Henrique Ordine",
"author_id": 1264138,
"author_profile": "https://Stackoverflow.com/users/1264138",
"pm_score": 4,
"selected": false,
"text": "EJB EJB POJO Serializable POJO's EJB serialVersionUID Caused by: java.io.IOException: Mismatched serialization UIDs : Source\n (Rep.\n IDRMI:com.hordine.pedra.softbudget.domain.Budget:5CF7CE11E6810A36:04A3FEBED5DA4588)\n = 04A3FEBED5DA4588 whereas Target (Rep. ID RMI:com.hordine.pedra.softbudget.domain.Budget:7AF5ED7A7CFDFF31:6227F23FA74A9A52)\n = 6227F23FA74A9A52\n"
},
{
"answer_id": 19418317,
"author": "Thalaivar",
"author_id": 337128,
"author_profile": "https://Stackoverflow.com/users/337128",
"pm_score": 6,
"selected": false,
"text": "SerialVersionUID JVM backward incompatibility Serializable InvalidClassException"
},
{
"answer_id": 22177263,
"author": "Archimedes Trajano",
"author_id": 242042,
"author_profile": "https://Stackoverflow.com/users/242042",
"pm_score": 4,
"selected": false,
"text": "serialVersionUID ObjectInputStream ObjectOutputStream HttpSession @SuppressWarnings(\"serial\")\n serialVersionUID Exception HttpServlet"
},
{
"answer_id": 31088833,
"author": "schnell18",
"author_id": 3061706,
"author_profile": "https://Stackoverflow.com/users/3061706",
"pm_score": 3,
"selected": false,
"text": "base_dir=$(pwd) \nsrc_dir=$base_dir/src/main/java \nic_api_cp=$base_dir/target/classes \n\nwhile read f \ndo \n clazz=${f//\\//.} \n clazz=${clazz/%.java/} \n seruidstr=$(serialver -classpath $ic_api_cp $clazz | cut -d ':' -f 2 | sed -e 's/^\\s\\+//')\n perl -ni.bak -e \"print $_; printf qq{%s\\n}, q{ private $seruidstr} if /public class/\" $src_dir/$f\ndone\n add_serialVersionUID.sh < myJavaToAmend.lst\n com/abc/ic/api/model/domain/item/BizOrderTransDO.java\ncom/abc/ic/api/model/domain/item/CardPassFeature.java\ncom/abc/ic/api/model/domain/item/CategoryFeature.java\ncom/abc/ic/api/model/domain/item/GoodsFeature.java\ncom/abc/ic/api/model/domain/item/ItemFeature.java\ncom/abc/ic/api/model/domain/item/ItemPicUrls.java\ncom/abc/ic/api/model/domain/item/ItemSkuDO.java\ncom/abc/ic/api/model/domain/serve/ServeCategoryFeature.java\ncom/abc/ic/api/model/domain/serve/ServeFeature.java\ncom/abc/ic/api/model/param/depot/DepotItemDTO.java\ncom/abc/ic/api/model/param/depot/DepotItemQueryDTO.java\ncom/abc/ic/api/model/param/depot/InDepotDTO.java\ncom/abc/ic/api/model/param/depot/OutDepotDTO.java\n"
},
{
"answer_id": 42641080,
"author": "roottraveller",
"author_id": 5167682,
"author_profile": "https://Stackoverflow.com/users/5167682",
"pm_score": 4,
"selected": false,
"text": "SerialVersionUID Serializable serialization SerialVersionUID SerialVersionUID SerialVersionUID SerialVersionUID SerialVersionUID private static final long Serializable java.io.Serializable Externalizable"
},
{
"answer_id": 48374672,
"author": "JegsVala",
"author_id": 3230563,
"author_profile": "https://Stackoverflow.com/users/3230563",
"pm_score": 6,
"selected": false,
"text": "Object serialVersionID serialVersionID InvalidClassCastException serialVersionUID serialVersionUID import java.io.Serializable;\n\npublic class Employee implements Serializable {\n private static final long serialVersionUID = 1L;\n private String empname;\n private byte empage;\n\n public String getEmpName() {\n return name;\n }\n\n public void setEmpName(String empname) {\n this.empname = empname;\n }\n\n public byte getEmpAge() {\n return empage;\n }\n\n public void setEmpAge(byte empage) {\n this.empage = empage;\n }\n\n public String whoIsThis() {\n return getEmpName() + \" is \" + getEmpAge() + \"years old\";\n }\n}\n import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectOutputStream;\n\npublic class Writer {\n public static void main(String[] args) throws IOException {\n Employee employee = new Employee();\n employee.setEmpName(\"Jagdish\");\n employee.setEmpAge((byte) 30);\n\n FileOutputStream fout = new\n FileOutputStream(\"/users/Jagdish.vala/employee.obj\");\n ObjectOutputStream oos = new ObjectOutputStream(fout);\n oos.writeObject(employee);\n oos.close();\n System.out.println(\"Process complete\");\n }\n}\n import java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\n\npublic class Reader {\n public static void main(String[] args) throws ClassNotFoundException, IOException {\n Employee employee = new Employee();\n FileInputStream fin = new FileInputStream(\"/users/Jagdish.vala/employee.obj\");\n ObjectInputStream ois = new ObjectInputStream(fin);\n employee = (Employee) ois.readObject();\n ois.close();\n System.out.println(employee.whoIsThis());\n }\n}\n private static final long serialVersionUID = 4L;\n Exception in thread \"main\" java.io.InvalidClassException: \ncom.jagdish.vala.java.serialVersion.Employee; local class incompatible: \nstream classdesc serialVersionUID = 1, local class serialVersionUID = 4\nat java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:616)\nat java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1623)\nat java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1518)\nat java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1774)\nat java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)\nat java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)\nat com.krishantha.sample.java.serialVersion.Reader.main(Reader.java:14)\n"
},
{
"answer_id": 54226923,
"author": "gagarwa",
"author_id": 3862024,
"author_profile": "https://Stackoverflow.com/users/3862024",
"pm_score": 2,
"selected": false,
"text": "serialVersionUID=1L serialVersionUID"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33203/"
] |
285,816
|
<p>I want to add items in a LaTeX-document. Say for example, that I want add hints to the document. I create a command, so I can call something similar to this:</p>
<pre><code>\hint{foocareful}{Be careful with foo!}{foo is a very precious item and can easily be broken. Be careful, especially don't throw foo.}
</code></pre>
<p>This will be formatted in special way, to make it easy for the reader to recognize it as a hint. It gets a label, that can be referenced in the example with 'foocareful'.</p>
<p>In the appendix I want to add a list of all hints with references to them. Something like:</p>
<pre><code>\begin{enumerate}
...
\item Be careful with foo! (\pageref{foocareful})
...
\end{enumerate}
</code></pre>
<p>But naturally I don't want to maintain this list by hand. How can I create automatically such a list?</p>
|
[
{
"answer_id": 286165,
"author": "Will Robertson",
"author_id": 4161,
"author_profile": "https://Stackoverflow.com/users/4161",
"pm_score": 4,
"selected": true,
"text": "float floatrow float \\documentclass{article}\n\\usepackage{float}\n\n\\floatstyle{boxed}\n\\newfloat{hintbox}{H}{hnt}\n\\floatname{hintbox}{Hint}\n\n\\newcommand\\hint[2]{%\n \\begin{hintbox}\n #2\n \\caption{#1}\n \\end{hintbox}}\n\n\\begin{document}\n\\section{Hello}\n\n\\hint{Be careful with foo!\\label{foocareful}}{%\n foo is a very precious item and can easily be broken. \n Be careful, especially don't throw foo.}\n\n\\hint{Don't worry about bar!\\label{foocareful}}{%\n Unlike foo, bar is pretty easily to get along with.}\n\n\\section{End}\n\n\\listof{hintbox}{List of Hints}\n\n\\end{document}\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] |
285,818
|
<p>With Java Version 1.5.0_06 on both Windows and Ubuntu Linux :</p>
<p>Whenever I add minutes to the date "2008/10/05 00:00:00" , it seems that an extra hour is wrongly added.</p>
<p>ie: adding 360 minutes to 2008/10/05 00:00:00 at midnight should arrive at 2008/10/05 06:00:00</p>
<p>But it is arriving at 2008/10/05 07:00:00</p>
<p>The totally perplexing thing is that this <strong>ONLY</strong> happens when the day is 2008/10/05, all other days that I try perform the minutes addition correctly. </p>
<p>Am I going crazy or is this a bug in Java ?</p>
<pre><code> SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
String date = "2008/10/05 00:00:00";
int minutesToAdd = 360; // 6 hrs
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(date));
cal.add(Calendar.MINUTE, minutesToAdd);
System.out.println(cal.getTime());
} catch (ParseException e) {}
</code></pre>
|
[
{
"answer_id": 68963768,
"author": "Ole V.V.",
"author_id": 5772882,
"author_profile": "https://Stackoverflow.com/users/5772882",
"pm_score": 0,
"selected": false,
"text": "private static final DateTimeFormatter PARSER\n = DateTimeFormatter.ofPattern(\"yyyy/MM/dd HH:mm:ss\", Locale.ROOT);\n String date = \"2008/10/05 00:00:00\";\n int minutesToAdd = 360; // 6 hrs\n \n ZonedDateTime originalTime = LocalDateTime.parse(date, PARSER)\n .atZone(ZoneId.of(\"Pacific/Auckland\"));\n ZonedDateTime newTime = originalTime.plusMinutes(minutesToAdd);\n \n System.out.println(newTime);\n ZonedDateTime plusHours plusMinutes"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27262/"
] |
285,829
|
<p>I'd like to use the DataGridView control as a list with columns. Sort of like ListView in Details mode but I want to keep the DataGridView flexibility.</p>
<p><strong>ListView</strong> (with <em>Details</em> view and <em>FullRowSelect</em> enabled) highlights the whole line and shows the focus mark around the whole line:<br>
<img src="https://i361.photobucket.com/albums/oo51/Stark3000/ListView_row.png" alt="selected row in ListView control"></p>
<p><strong>DataGridView</strong> (with <em>SelectionMode</em> = <em>FullRowSelect</em>) displays focus mark only around a single cell:<br>
<img src="https://i361.photobucket.com/albums/oo51/Stark3000/DataGridView_row.png" alt="selected row in DataGridView"></p>
<p>So, does anyone know of some (ideally) easy way to make the DataGridView row selection look like the ListView one?<br>
I'm not looking for a changed behaviour of the control - I only want it to look the same.<br>
Ideally, without messing up with the methods that do the actual painting.</p>
|
[
{
"answer_id": 331438,
"author": "Tomas Sedovic",
"author_id": 2239,
"author_profile": "https://Stackoverflow.com/users/2239",
"pm_score": 7,
"selected": true,
"text": "dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;\ndgv.MultiSelect = false;\ndgv.RowPrePaint +=new DataGridViewRowPrePaintEventHandler(dgv_RowPrePaint);\n private void dgv_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)\n{\n e.PaintParts &= ~DataGridViewPaintParts.Focus;\n}\n"
},
{
"answer_id": 8304512,
"author": "L.E.",
"author_id": 205291,
"author_profile": "https://Stackoverflow.com/users/205291",
"pm_score": 5,
"selected": false,
"text": "SelectionMode == FullRowSelect\n ReadOnly == true\n"
},
{
"answer_id": 67304346,
"author": "igorsp7",
"author_id": 8239268,
"author_profile": "https://Stackoverflow.com/users/8239268",
"pm_score": 0,
"selected": false,
"text": "private void gvMain_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)\n{\n // Draw our own focus rectangle around the entire row\n if (gvMain.Rows[e.RowIndex].Selected && gvMain.Focused) \n ControlPaint.DrawFocusRectangle(e.Graphics, e.RowBounds, Color.Empty, gvMain.DefaultCellStyle.SelectionBackColor);\n}\n\nprivate void gvMain_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)\n{\n // Disable the original focus rectangle around the cell\n e.PaintParts &= ~DataGridViewPaintParts.Focus;\n}\n\nprivate void gvMain_LeaveAndEnter(object sender, EventArgs e)\n{\n // Redraw our focus rectangle every time our DataGridView receives and looses focus (same event handler for both events)\n gvMain.InvalidateRow(gvMain.CurrentRow.Index);\n}\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2239/"
] |
285,837
|
<p>My company is in the process of rewriting our software from scratch, and I'm the one who is going to be doing most of the work in rewriting the Mac client (The core of our software is Windows based, and the Mac client communicates with it through a webservice).</p>
<p>This isn't a real heavy app, mainly does some background work tracking stuff and a UI component for the user to enter information.</p>
<p>I'm trying to decide how hard I should argue for dropping support for 10.4 and going with pure 10.5+/Obj-C 2.0 code.</p>
<p>My main motivations for this are:</p>
<ul>
<li><p>It would be easier to code, I could use all the features of Obj-C 2.0 such as synthesized properties and fast enumeration.</p></li>
<li><p>It would give me access to several classes, and methods in existing classes, that don't exist in 10.4 (Just in mocking up a UI I've come across NSPathControl and NSTreeNode, both of which I would otherwise be very happy to use.</p></li>
<li><p>Preparing for the conversion to 64 bit coming in Snow Leopard. It seems like most of the techniques for <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/Cocoa64BitGuide/64BitChangesCocoa/chapter_3_section_2.html#//apple_ref/doc/uid/TP40004247-CH4-DontLinkElementID_1" rel="nofollow noreferrer">preparing for the move to 64 bit</a> (NSInteger, etc) are only available in 10.5+, and it would not be possible to use these if writing for 10.4.</p></li>
</ul>
<p>The downside would of course be that we'd no longer be supporting an operating system that was only a year out of date.</p>
<p>My boss is himself supportive of this move, but of course has our customers to consider and doesn't want to cause any more issues for them than are justified. The director of support would like to support 10.4. I suspect the other execs will be marginally against it at first, just due to the not being able to support some customers thing. Everybody would be open to persuasion by a good argument from either side.</p>
<p>I'm trying to talk to some of the support people and get an idea of how many of our customers are actually still using 10.4, but I don't have that data yet.</p>
<p>Some kind of hybrid solution might be possible, such as rewriting parts of the old client to use the new webservice, or writing the client in 10.5 and backporting it to 10.4 if enough people made a fuss, but quite frankly those sound like they're likely to be even more trouble than giving up the 10.5 features and writing the code in 10.4 to begin with.</p>
<p>So I guess my questions are as follows:</p>
<ol>
<li><p>Given the information above, do you think making a case for the adoption of 10.5+ only is the right thing to do? Do you have any suggestions as to how this might be presented positively to the rest of the company?</p></li>
<li><p>I don't know as much about the coming 64 bit transition as I'd like. Does anybody have any good references on what will be different, and do you think that supporting only 10.5+ would make this transition easier for us?</p></li>
</ol>
|
[
{
"answer_id": 285878,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 1,
"selected": false,
"text": "NSTask NSPipe .nib -(id)init\n{\n BOOL tiger = floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_4; \n NSString nibname = (tiger ? @\"WindowTiger\" : @\"WindowLeopard\");\n if (self = [super initWithWindowNibName:nibname]) \n …\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] |
285,860
|
<p>Using Java, how can I test that a URL is contactable, and returns a valid response?</p>
<pre><code>http://stackoverflow.com/about
</code></pre>
|
[
{
"answer_id": 285862,
"author": "brasskazoo",
"author_id": 6340,
"author_profile": "https://Stackoverflow.com/users/6340",
"pm_score": 7,
"selected": true,
"text": "public void testURL() throws Exception {\n String strUrl = \"http://stackoverflow.com/about\";\n\n try {\n URL url = new URL(strUrl);\n HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();\n urlConn.connect();\n\n assertEquals(HttpURLConnection.HTTP_OK, urlConn.getResponseCode());\n } catch (IOException e) {\n System.err.println(\"Error creating HTTP connection\");\n e.printStackTrace();\n throw e;\n }\n}\n"
},
{
"answer_id": 6452098,
"author": "Charif",
"author_id": 811943,
"author_profile": "https://Stackoverflow.com/users/811943",
"pm_score": -1,
"selected": false,
"text": "import org.apache.commons.validator.UrlValidator;\n\npublic class ValidateUrlExample {\n\n public static void main(String[] args) {\n\n UrlValidator urlValidator = new UrlValidator();\n\n //valid URL\n if (urlValidator.isValid(\"http://www.mkyong.com\")) {\n System.out.println(\"url is valid\");\n } else {\n System.out.println(\"url is invalid\");\n }\n\n //invalid URL\n if (urlValidator.isValid(\"http://invalidURL^$&%$&^\")) {\n System.out.println(\"url is valid\");\n } else {\n System.out.println(\"url is invalid\");\n }\n }\n}\n"
},
{
"answer_id": 61655279,
"author": "Sam Ginrich",
"author_id": 9437799,
"author_profile": "https://Stackoverflow.com/users/9437799",
"pm_score": 0,
"selected": false,
"text": "System.out.println(new InetSocketAddress(\"http://stackoverflow.com/about\", 80).isUnresolved());\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
] |
285,866
|
<p>I want to create an Ant buildfile, that includes some files as a sort of plugin.</p>
<p>So if I want to activate a feature in a project - say pmd-checking - I copy a pmd.xml in a directory and the build.xml get on the start the idea, that pmd.xml exists and imports it, so that new targets can be available to the build.</p>
<p>But the 'import' task can only be used as a top-level task, so I have no idea how to relize this functionality. Is this possible with Ant and if so, how can I do it?</p>
<p>EDIT: I would prefer a solution, that allows new targets to show up in the listing presented by <code>ant -p</code>.</p>
|
[
{
"answer_id": 285951,
"author": "Miguel Ping",
"author_id": 22992,
"author_profile": "https://Stackoverflow.com/users/22992",
"pm_score": 2,
"selected": false,
"text": "<ant antfile=\"plugins/pmd.xml\" target=\"${pmd-target}\"/>\n"
},
{
"answer_id": 286008,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "-p <if>"
},
{
"answer_id": 286106,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 2,
"selected": false,
"text": "optional true pmd.xml ant -p"
},
{
"answer_id": 4639766,
"author": "martin clayton",
"author_id": 183172,
"author_profile": "https://Stackoverflow.com/users/183172",
"pm_score": 3,
"selected": true,
"text": "ant -p <property name=\"plugins.dir\" value=\"plugins\" />\n<fileset id=\"plugin.modules\" dir=\"${plugins.dir}\">\n <include name=\"**/*.xml\" />\n</fileset>\n\n<import>\n <fileset refid=\"plugin.modules\" />\n</import>\n empty.xml <project />\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] |
285,869
|
<p>Does anyone know how to use the <a href="http://msdn.microsoft.com/en-us/library/ms645543(VS.85).aspx" rel="nofollow noreferrer">Raw Input</a> facility on Windows from a WX Python application?</p>
<p>What I need to do is be able to differentiate the input from multiple keyboards. So if there is another way to achieving that, that would work too.</p>
|
[
{
"answer_id": 307018,
"author": "joeforker",
"author_id": 36330,
"author_profile": "https://Stackoverflow.com/users/36330",
"pm_score": 3,
"selected": true,
"text": ">>> import ctypes\n>>> ctypes.windll.user32.RegisterRawInputDevices\n<_FuncPtr object at 0x01FCFDC8>\n"
}
] |
2008/11/12
|
[
"https://Stackoverflow.com/questions/285869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10286/"
] |
285,886
|
<p>I'm not talking about a pointer to an instance, I want a pointer to a class itself.</p>
|
[
{
"answer_id": 285894,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 5,
"selected": true,
"text": "type_info"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/285886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37181/"
] |
285,889
|
<p>I want to create a file on the webserver dynamically in PHP.</p>
<p>First I create a directory to store the file. THIS WORKS</p>
<pre><code>// create the users directory and index page
$dirToCreate = "..".$_SESSION['s_USER_URL'];
mkdir($dirToCreate, 0777, TRUE); // create the directory for the user
</code></pre>
<p>Now I want to create a file called index.php and write out some content into it.</p>
<p>I am trying:</p>
<pre><code>$ourFileName = $_SESSION['s_USER_URL']."/"."index.php";
$ourFileHandle = fopen($ourFileName, 'x') or die("can't open file");
fclose($ourFileHandle);
// append data to it
$ourFileHandle = fopen($ourFileName, 'a') or die("can't write to file");
$stringData = "Hi";
fwrite($ourFileHandle, $stringData);
</code></pre>
<p>But it never gets past the <code>$ourFileHandle = fopen($ourFileName, 'x') or die("can't open file");</code> Saying the file does not exist, but that is the point. I want to create it.</p>
<p>I did some echoing and the path (/people/jason) exists and I am trying to write to /people/jason/index.php</p>
<p>Does anyone have any thoughts on what I am doing wrong? </p>
<p>PHP 5 on a linux server I believe.</p>
<p>-Jason</p>
|
[
{
"answer_id": 285905,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 4,
"selected": true,
"text": "$dirToCreate = \"..\".$_SESSION['s_USER_URL']; \n $ourFileName = $_SESSION['s_USER_URL'].\"/\".\"index.php\";\n $ourFileName = '..' . $_SESSION['s_USER_URL'] . '/index.php';\n $ourFileName = $dirToCreate . '/index.php';\n"
},
{
"answer_id": 285906,
"author": "Kris",
"author_id": 18565,
"author_profile": "https://Stackoverflow.com/users/18565",
"pm_score": 0,
"selected": false,
"text": "file_put_contents( $filename, $content )\n touch"
},
{
"answer_id": 286114,
"author": "John T",
"author_id": 36457,
"author_profile": "https://Stackoverflow.com/users/36457",
"pm_score": 0,
"selected": false,
"text": "<?php\n\n$path = \"..\".$_SESSION['s_USER_URL']; \n// may want to add a tilde (~) to user directory\n// path, unixy thing to do ;D\n\nmkdir($path, 0777); // make directory, set perms.\n\n$file = \"index.php\"; // declare a file name\n\n/* here you could use the chdir() command, if you wanted to go to the \ndirectory where you created the file, this will help you understand the \nrest of your code as you will have to perform less concatenation on\n directories such as below */\n\n$handle = fopen($path.\"/\".$file, 'w') or die(\"can't open file\");\n// open file for writing, create if it doesn't exist\n\n$info = \"Stack Overflow was here!\"; // string to input\n\nfwrite($handle, $info); // perform the write operation\n\nfclose($handle); // close the handle\n\n?>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/285889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
285,928
|
<pre><code> private void activateRecords(long[] stuff) {
...
api.activateRecords(Arrays.asList(specIdsToActivate));
}
</code></pre>
<p>Shouldn't this call to Arrays.asList return a list of <code>Long</code>s? Instead it is returning a <code>List<long[]></code></p>
<pre><code>public static <T> List<T> asList(T... a)
</code></pre>
<p>The method signature is consistent with the results, the varargs throws the entire array into the list. It's the same as <code>new ArrayList(); list.add(myArray)</code> And yes, I know it's meant to be used like this: <code>Arrays.asList(T t1, T t2, T t3)</code></p>
<p>I guess what I'm getting at, is instead of the varargs form, why can't I just have my old asList method (at least I think this is how it used to work) that would take the contents and put them individually into a list? Any other <strong>clean</strong> way of doing this?</p>
|
[
{
"answer_id": 285969,
"author": "Stephen",
"author_id": 37193,
"author_profile": "https://Stackoverflow.com/users/37193",
"pm_score": 3,
"selected": false,
"text": "private List<Long> array(final long[] lngs) {\n List<Long> list = new ArrayList<Long>();\n for (long l : lngs) {\n list.add(l);\n }\n return list;\n}\n private List<Long> array(final long[] lngs) {\n List<Long> list = new ArrayList<Long>();\n for (Long l : lngs) {\n list.add(l);\n }\n return list;\n}\n Long l = 1l;\n Long[] ls = new long[]{1l}\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/285928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402777/"
] |
285,937
|
<p>Is it possible to insert a row, but only if one of the values already in the table does not exist?</p>
<p>I'm creating a <em>Tell A Friend</em> with referral points for an ecommerce system, where I need to insert the friend's email into the database table, but only if it doesn't already exist in the table. This is because I don't want any more than 1 person getting the referral points once the new customer signs up and purchases something. Therefore I want only one email ever once in the table.</p>
<p>I'm using PHP 4 and MySql 4.1.</p>
|
[
{
"answer_id": 285953,
"author": "José Leal",
"author_id": 37190,
"author_profile": "https://Stackoverflow.com/users/37190",
"pm_score": 1,
"selected": false,
"text": "try {\n mysql_query($sql);\n}\ncatch(Exception $e) {\n\n}\n"
},
{
"answer_id": 285957,
"author": "victoriah",
"author_id": 37014,
"author_profile": "https://Stackoverflow.com/users/37014",
"pm_score": 5,
"selected": true,
"text": "INSERT INTO table (email) VALUES (email_address) ON DUPLICATE KEY UPDATE\nemail=email_address\n"
},
{
"answer_id": 285964,
"author": "Gene",
"author_id": 35630,
"author_profile": "https://Stackoverflow.com/users/35630",
"pm_score": 3,
"selected": false,
"text": "IF NOT EXISTS(SELECT * FROM myTable WHERE Email=@Email) THEN INSERT INTO blah blah\n"
},
{
"answer_id": 285980,
"author": "Todd",
"author_id": 31940,
"author_profile": "https://Stackoverflow.com/users/31940",
"pm_score": 5,
"selected": false,
"text": "INSERT IGNORE INTO Table (EmailAddr) VALUES ('test@test.com')\n"
},
{
"answer_id": 903006,
"author": "mttmllns",
"author_id": 110926,
"author_profile": "https://Stackoverflow.com/users/110926",
"pm_score": 2,
"selected": false,
"text": "INSERT INTO table (email) VALUES (email_address)\nON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)\n email=email_address LAST_INSERT_ID()"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/285937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31671/"
] |
285,938
|
<p>Given an HTML link like</p>
<pre><code><a href="urltxt" class="someclass" close="true">texttxt</a>
</code></pre>
<p>how can I isolate the url and the text? </p>
<p><strong>Updates</strong></p>
<p>I'm using Beautiful Soup, and am unable to figure out how to do that. </p>
<p>I did </p>
<pre><code>soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
links = soup.findAll('a')
for link in links:
print "link content:", link.content," and attr:",link.attrs
</code></pre>
<p>i get </p>
<pre><code>*link content: None and attr: [(u'href', u'_redirectGeneric.asp?genericURL=/root /support.asp')]* ...
...
</code></pre>
<p>Why am i missing the content? </p>
<p>edit: elaborated on 'stuck' as advised :)</p>
|
[
{
"answer_id": 285941,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 4,
"selected": true,
"text": "soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read())\n import urlparse, urllib\nfrom BeautifulSoup import BeautifulSoup\n\nurl = \"http://www.example.com/index.html\"\nsource = urllib.urlopen(url).read()\n\nsoup = BeautifulSoup(source)\n\nfor item in soup.fetchall('a'):\n try:\n link = urlparse.urlparse(item['href'].lower())\n except:\n # Not a valid link\n pass\n else:\n print link\n"
},
{
"answer_id": 285959,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 3,
"selected": false,
"text": "soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))\nfor link in soup.findAll('a'):\n print link.attrs, link.contents\n"
},
{
"answer_id": 285963,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "/<a\\s+[^>]*?href=\"([^\"]*)\".*?>(.*?)<\\/a>/\n '<a href=\"url\" close=\"true\">text</a>'\n// Parts: \"url\", \"text\"\n\n'<a href=\"url\" close=\"true\">text<span>something</span></a>'\n// Parts: \"url\", \"text<span>something</span>\"\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/285938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19731/"
] |
285,955
|
<p>Does anybody have a snippet of Java that can return the newest file in a directory (or knowledge of a library that simplifies this sort of thing)?</p>
|
[
{
"answer_id": 285987,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 1,
"selected": false,
"text": "import java.io.File;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\n\npublic class Newest {\n public static void main(String[] args) {\n File dir = new File(\"C:\\\\your\\\\dir\");\n File [] files = dir.listFiles();\n Arrays.sort(files, new Comparator(){\n public int compare(Object o1, Object o2) {\n return compare( (File)o1, (File)o2);\n }\n private int compare( File f1, File f2){\n long result = f2.lastModified() - f1.lastModified();\n if( result > 0 ){\n return 1;\n } else if( result < 0 ){\n return -1;\n } else {\n return 0;\n }\n }\n });\n System.out.println( Arrays.asList(files ));\n }\n}\n"
},
{
"answer_id": 286001,
"author": "José Leal",
"author_id": 37190,
"author_profile": "https://Stackoverflow.com/users/37190",
"pm_score": 6,
"selected": false,
"text": "public static File getLastModified(String directoryFilePath)\n{\n File directory = new File(directoryFilePath);\n File[] files = directory.listFiles(File::isFile);\n long lastModifiedTime = Long.MIN_VALUE;\n File chosenFile = null;\n\n if (files != null)\n {\n for (File file : files)\n {\n if (file.lastModified() > lastModifiedTime)\n {\n chosenFile = file;\n lastModifiedTime = file.lastModified();\n }\n }\n }\n\n return chosenFile;\n}\n Java 8"
},
{
"answer_id": 12337559,
"author": "John Jintire",
"author_id": 1657856,
"author_profile": "https://Stackoverflow.com/users/1657856",
"pm_score": 4,
"selected": false,
"text": "import org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.comparator.LastModifiedFileComparator;\nimport org.apache.commons.io.filefilter.WildcardFileFilter;\n\n...\n\n/* Get the newest file for a specific extension */\npublic File getTheNewestFile(String filePath, String ext) {\n File theNewestFile = null;\n File dir = new File(filePath);\n FileFilter fileFilter = new WildcardFileFilter(\"*.\" + ext);\n File[] files = dir.listFiles(fileFilter);\n\n if (files.length > 0) {\n /** The newest file comes first **/\n Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);\n theNewestFile = files[0];\n }\n\n return theNewestFile;\n}\n"
},
{
"answer_id": 30892976,
"author": "Almaz",
"author_id": 4989585,
"author_profile": "https://Stackoverflow.com/users/4989585",
"pm_score": 5,
"selected": false,
"text": "Path dir = Paths.get(\"./path/somewhere\"); // specify your directory\n\nOptional<Path> lastFilePath = Files.list(dir) // here we get the stream with full directory listing\n .filter(f -> !Files.isDirectory(f)) // exclude subdirectories from listing\n .max(Comparator.comparingLong(f -> f.toFile().lastModified())); // finally get the last file using simple comparator by lastModified field\n\nif ( lastFilePath.isPresent() ) // your folder may be empty\n{\n // do your code here, lastFilePath contains all you need\n} \n"
},
{
"answer_id": 45711591,
"author": "Prasanth V",
"author_id": 6370767,
"author_profile": "https://Stackoverflow.com/users/6370767",
"pm_score": 2,
"selected": false,
"text": "private File getLatestFilefromDir(String dirPath){\n File dir = new File(dirPath);\n File[] files = dir.listFiles();\n if (files == null || files.length == 0) {\n return null;\n }\n\n File lastModifiedFile = files[0];\n for (int i = 1; i < files.length; i++) {\n if (lastModifiedFile.lastModified() < files[i].lastModified()) {\n lastModifiedFile = files[i];\n }\n }\n return lastModifiedFile;\n}\n"
},
{
"answer_id": 45996832,
"author": "Tested",
"author_id": 8547291,
"author_profile": "https://Stackoverflow.com/users/8547291",
"pm_score": 1,
"selected": false,
"text": "public File getLastDownloadedFile() {\n File choice = null;\n try {\n File fl = new File(\"C:/Users/\" + System.getProperty(\"user.name\")\n + \"/Downloads/\");\n File[] files = fl.listFiles(new FileFilter() {\n public boolean accept(File file) {\n return file.isFile();\n }\n });\n//Sleep to download file if not required can be removed\n Thread.sleep(30000);\n long lastMod = Long.MIN_VALUE;\n\n for (File file : files) {\n if (file.lastModified() > lastMod) {\n choice = file;\n lastMod = file.lastModified();\n }\n }\n } catch (Exception e) {\n System.out.println(\"Exception while getting the last download file :\"\n + e.getMessage());\n }\n System.out.println(\"The last downloaded file is \" + choice.getPath());\n System.out.println(\"The last downloaded file is \" + choice.getPath(),true);\n return choice;\n}\n"
},
{
"answer_id": 51330320,
"author": "Asheron",
"author_id": 10027688,
"author_profile": "https://Stackoverflow.com/users/10027688",
"pm_score": 0,
"selected": false,
"text": "public static File lastFileModified(String dir) {\n File fl = new File(dir);\n File choice = null;\n if (fl.listFiles().length>0) {\n File[] files = fl.listFiles(new FileFilter() {\n public boolean accept(File file) {\n return file.isFile();\n }\n });\n long lastMod = Long.MIN_VALUE;\n\n for (File file : files) {\n if (file.lastModified() > lastMod) {\n choice = file;\n lastMod = file.lastModified();\n }\n }\n }\n return choice;\n}\n"
},
{
"answer_id": 55561917,
"author": "theeman05",
"author_id": 10711647,
"author_profile": "https://Stackoverflow.com/users/10711647",
"pm_score": 1,
"selected": false,
"text": "import java.nio.file.Files;\nimport java.nio.file.attribute.BasicFileAttributes;\nimport java.nio.file.attribute.FileTime;\n\nprivate File lastFileCreated(String dir) {\n File fl = new File(dir);\n File[] files = fl.listFiles(new FileFilter() {\n public boolean accept(File file) {\n return true;\n }\n });\n\n FileTime lastCreated = null;\n File choice = null;\n\n for (File file : files) {\n BasicFileAttributes attr=null;\n try {\n attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);\n }catch (Exception e){\n System.out.println(e);\n }\n\n if(lastCreated ==null)\n lastCreated = attr.creationTime();\n\n if (attr!=null&&attr.creationTime().compareTo(lastCreated)==0) {\n choice = file;\n }\n }\n return choice;\n}\n"
},
{
"answer_id": 56402466,
"author": "SaurabhGuptaAricent",
"author_id": 11585199,
"author_profile": "https://Stackoverflow.com/users/11585199",
"pm_score": 0,
"selected": false,
"text": "public String pickLatestFileFromDownloads() {\n\n String currentUsersHomeDir = System.getProperty(\"user.home\");\n\n String downloadFolder = currentUsersHomeDir + File.separator + \"Downloads\" + File.separator;\n\n File dir = new File(downloadFolder);\n File[] files = dir.listFiles();\n if (files == null || files.length == 0) {\n testLogger.info(\"There is no file in the folder\");\n }\n\n File lastModifiedFile = files[0];\n for (int i = 1; i < files.length; i++) {\n if (lastModifiedFile.lastModified() < files[i].lastModified()) {\n lastModifiedFile = files[i];\n }\n }\n String k = lastModifiedFile.toString();\n\n System.out.println(lastModifiedFile);\n Path p = Paths.get(k);\n String file = p.getFileName().toString();\n return file;\n\n }\n\n//PostedBy: saurabh Gupta Aricent-provar\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/285955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
285,960
|
<p>The <code>equals()</code> method of the URL class in the Java class library makes a DNS request to get the IP for the hostname, to check the two IP's for equality. This happens even for URLs that are created from the same <code>String</code>. Is there a way to avoid this internet access?</p>
|
[
{
"answer_id": 285967,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 1,
"selected": false,
"text": "equals"
},
{
"answer_id": 285975,
"author": "Rick",
"author_id": 14138,
"author_profile": "https://Stackoverflow.com/users/14138",
"pm_score": 2,
"selected": false,
"text": "url1.toString().equals(url2.toString())\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/285960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] |
285,990
|
<p>In .Net, I found this great library, <a href="http://www.codeplex.com/htmlagilitypack" rel="noreferrer">HtmlAgilityPack</a> that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?</p>
|
[
{
"answer_id": 289167,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 4,
"selected": true,
"text": ">>> from elementtidy.TidyHTMLTreeBuilder import TidyHTMLTreeBuilder as TB\n>>> tb = TB()\n>>> tb.feed(\"<p>Hello world\")\n>>> e= tb.close()\n>>> e.find(\".//{http://www.w3.org/1999/xhtml}p\")\n<Element {http://www.w3.org/1999/xhtml}p at 264eb8>\n"
},
{
"answer_id": 4747067,
"author": "Jagtesh Chadha",
"author_id": 129912,
"author_profile": "https://Stackoverflow.com/users/129912",
"pm_score": 6,
"selected": false,
"text": ">>> from lxml import etree\n>>> doc = '<foo><bar></bar></foo>'\n>>> tree = etree.HTML(doc)\n\n>>> r = tree.xpath('/foo/bar')\n>>> len(r)\n1\n>>> r[0].tag\n'bar'\n\n>>> r = tree.xpath('bar')\n>>> r[0].tag\n'bar'\n"
},
{
"answer_id": 9441191,
"author": "Gareth Davidson",
"author_id": 146642,
"author_profile": "https://Stackoverflow.com/users/146642",
"pm_score": 3,
"selected": false,
"text": "from lxml.html.soupparser import fromstring\ntree = fromstring('<mal form=\"ed\"><html/>here!')\nmatches = tree.xpath(\"./mal[@form=ed]\")\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/285990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30529/"
] |
286,004
|
<p>There seem to be a decent number of <code>mod_rewrite</code> threads floating around lately with a bit of confusion over how certain aspects of it work. As a result I've compiled a few notes on common functionality, and perhaps a few annoying nuances.</p>
<p>What other features / common issues have you run across using <code>mod_rewrite</code>?</p>
|
[
{
"answer_id": 286005,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 8,
"selected": false,
"text": "mod_rewrite httpd.conf .htaccess httpd.conf .htaccess httpd.conf <Virtual Host> # logs can't be enabled from .htaccess\n# loglevel > 2 is really spammy!\nRewriteLog /path/to/rewrite.log\nRewriteLogLevel 2\n RewriteEngine on\n# ignore existing files\nRewriteCond %{REQUEST_FILENAME} !-f \n# ignore existing directories\nRewriteCond %{REQUEST_FILENAME} !-d \n# map requests to index.php and append as a query string\nRewriteRule ^(.*)$ index.php?query=$1 \n FallbackResource RewriteEngine on\n# 302 Temporary Redirect (302 is the default, but can be specified for clarity)\nRewriteRule ^oldpage\\.html$ /newpage.html [R=302] \n# 301 Permanent Redirect\nRewriteRule ^oldpage2\\.html$ /newpage.html [R=301] \n # this rule:\nRewriteRule ^somepage\\.html$ http://google.com\n# is equivalent to:\nRewriteRule ^somepage\\.html$ http://google.com [R]\n# and:\nRewriteRule ^somepage\\.html$ http://google.com [R=302]\n RewriteEngine on\nRewriteCond %{HTTPS} off\nRewriteRule ^(.*)$ https://example.com/$1 [R,L]\n [R] [redirect] [R=301] [redirect=301] [L] [last] [NC] [nocase] RewriteRule ^olddir(.*)$ /newdir$1 [L,NC]\n mod_alias mod_rewrite # Bad\nRedirect 302 /somepage.html http://example.com/otherpage.html\nRewriteEngine on\nRewriteRule ^(.*)$ index.php?query=$1\n\n# Good (use mod_rewrite for both)\nRewriteEngine on\n# 302 redirect and stop processing\nRewriteRule ^somepage.html$ /otherpage.html [R=302,L] \nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\n# handle other redirects\nRewriteRule ^(.*)$ index.php?query=$1 \n mod_alias mod_rewrite .htaccess # given: GET /directory/file.html\n\n# .htaccess\n# result: /newdirectory/file.html\nRewriteRule ^directory(.*)$ /newdirectory$1\n\n# .htaccess\n# result: no match!\nRewriteRule ^/directory(.*)$ /newdirectory$1\n\n# httpd.conf\n# result: /newdirectory/file.html\nRewriteRule ^/directory(.*)$ /newdirectory$1\n\n# Putting a \"?\" after the slash will allow it to work in both contexts:\nRewriteRule ^/?directory(.*)$ /newdirectory$1\n [L] .htaccess <Directory> [L] # processing does not stop here\nRewriteRule ^dirA$ /dirB [L] \n# /dirC will be the final result\nRewriteRule ^dirB$ /dirC \n rewrite 'dirA' -> '/dirB'\ninternal redirect with /dirB [INTERNAL REDIRECT]\nrewrite 'dirB' -> '/dirC'\n [END] [L] [END] [L] RewriteCond # Only process the following RewriteRule if on the first pass\nRewriteCond %{ENV:REDIRECT_STATUS} ^$\nRewriteRule ...\n httpd.conf"
},
{
"answer_id": 1298917,
"author": "Michael Ekoka",
"author_id": 56974,
"author_profile": "https://Stackoverflow.com/users/56974",
"pm_score": 4,
"selected": false,
"text": "Options -MultiViews\n RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^(.*)$ file1.php/$1 \n Options +FollowSymLinks \n"
},
{
"answer_id": 1298953,
"author": "B.E.",
"author_id": 94162,
"author_profile": "https://Stackoverflow.com/users/94162",
"pm_score": 2,
"selected": false,
"text": "RewriteMap examplemap txt:/path/to/file/map.txt\n RewriteRule ^/ex/(.*) ${examplemap:$1}\n"
},
{
"answer_id": 1338657,
"author": "Sean McMillan",
"author_id": 117587,
"author_profile": "https://Stackoverflow.com/users/117587",
"pm_score": 4,
"selected": false,
"text": "RewriteBase /\n"
},
{
"answer_id": 2097329,
"author": "DrDol",
"author_id": 254234,
"author_profile": "https://Stackoverflow.com/users/254234",
"pm_score": 3,
"selected": false,
"text": "RewriteCond %{REQUEST_URI} ^/(server0|server1).*$ [NC]\n# %1 is the string that was found above\n# %1<>%{HTTP_COOKIE} concatenates first macht with mod_rewrite variable -> \"test0<>foo=bar;\"\n#RewriteCond search for a (.*) in the second part -> \\1 is a reference to (.*)\n# <> is used as an string separator/indicator, can be replaced by any other character\nRewriteCond %1<>%{HTTP_COOKIE} !^(.*)<>.*stickysession=\\1.*$ [NC]\nRewriteRule ^(.*)$ https://notmatch.domain.com/ [R=301,L]\n RewriteCond %{HTTP_COOKIE} ^.*stickysession=route\\.server([0-9]{1,2}).*$ [NC]\nRewriteRule (.*) https://worker%1.internal.com/$1 [P,L]\n"
},
{
"answer_id": 2688558,
"author": "mromaine",
"author_id": 228162,
"author_profile": "https://Stackoverflow.com/users/228162",
"pm_score": 5,
"selected": false,
"text": "RewriteCond %{ENV:REDIRECT_STATUS} ^$\n"
},
{
"answer_id": 21733589,
"author": "cweekly",
"author_id": 385848,
"author_profile": "https://Stackoverflow.com/users/385848",
"pm_score": 2,
"selected": false,
"text": "RewriteCond %{HTTP_COOKIE} myCookie=(a|b) [NC]\nRewriteRule .* - [E=MY_ENV_VAR:%b]\n RewriteRule [R] RewriteRule .* - [R=503,L]\n ProxyPass RewriteRule ^/(.*)$ balancer://cluster%{REQUEST_URI} [P,QSA,L]\n RewriteRule RewriteCond"
},
{
"answer_id": 26929985,
"author": "JaredC",
"author_id": 339532,
"author_profile": "https://Stackoverflow.com/users/339532",
"pm_score": 2,
"selected": false,
"text": "<Directory> <Directory> <Directory>"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4853/"
] |
286,007
|
<p>I need to configure Tomcat memory settings as part of a larger installation, so manually configuring tomcat with the configuration app after the fact is out of the question. I thought I could just throw the JVM memory settings into the JAVA_OPTS environment variable, but I'm testing that with jconsole to see if it works and it... doesn't.</p>
<p>As per the comment below, CATALINA_OPTS doesn't work either. So far, the only way I can get it to work is via the Tomcat configuration GUI, and that's not an acceptable solution for my problem.</p>
|
[
{
"answer_id": 286011,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 3,
"selected": false,
"text": "CATALINA_OPTS"
},
{
"answer_id": 286415,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 1,
"selected": false,
"text": "HKLM\\SOFTWARE\\Apache Software Foundation\\Procrun 2.0\\Tomcat6\\Parameters\\Java"
},
{
"answer_id": 299590,
"author": "Cozzman",
"author_id": 18191,
"author_profile": "https://Stackoverflow.com/users/18191",
"pm_score": 2,
"selected": false,
"text": "tomcat5 //US//Tomcat5 --JvmMx=512\n"
},
{
"answer_id": 338019,
"author": "Glenn",
"author_id": 29771,
"author_profile": "https://Stackoverflow.com/users/29771",
"pm_score": 7,
"selected": true,
"text": "export JAVA_OPTS=\"-server -Xmx512m\"\n set JAVA_OPTS=-server -Xmx768m\n"
},
{
"answer_id": 3652561,
"author": "Dmitriy Kochergin",
"author_id": 431501,
"author_profile": "https://Stackoverflow.com/users/431501",
"pm_score": 2,
"selected": false,
"text": "setenv.bat ==============setenv.bat============\n\n set JAVA_OPTS=-XX:MaxPermSize=256m -Xms256M -Xmx768M -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=7777,server=y,suspend=n %JAVA_OPTS%\n\n====================================\n JAVA_OPTS"
},
{
"answer_id": 3964598,
"author": "DrTune",
"author_id": 479935,
"author_profile": "https://Stackoverflow.com/users/479935",
"pm_score": 2,
"selected": false,
"text": "export CATALINA_OPTS=\"-Xmx`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.75 } '`k\"\n"
},
{
"answer_id": 8111885,
"author": "Ondrej Kvasnovsky",
"author_id": 931428,
"author_profile": "https://Stackoverflow.com/users/931428",
"pm_score": 2,
"selected": false,
"text": "`cat /proc/meminfo | grep MemTotal | awk '{\n print $2*0.75 } '` `cat /proc/meminfo | grep MemTotal | awk '{\n print $2*0.75 } '` `cat /proc/meminfo | grep MemTotal |\n awk '{ print $2*0.15 } '` `cat /proc/meminfo | grep\n MemTotal | awk '{ print $2*0.15 } '` `cat /proc/meminfo\n | grep MemTotal | awk '{ print $2*0.15 } '` `cat\n /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`"
},
{
"answer_id": 8207031,
"author": "martinusadyh",
"author_id": 563694,
"author_profile": "https://Stackoverflow.com/users/563694",
"pm_score": 3,
"selected": false,
"text": "# -----------------------------------------------------------------------------\n\nJAVA_OPTS=\"-Djava.awt.headless=true -Dfile.encoding=UTF-8 -server -Xms1024m \\\n-Xmx1024m -XX:NewSize=512m -XX:MaxNewSize=512m -XX:PermSize=512m \\\n-XX:MaxPermSize=512m -XX:+DisableExplicitGC\"\n"
},
{
"answer_id": 10391630,
"author": "Sailab Rahi",
"author_id": 470848,
"author_profile": "https://Stackoverflow.com/users/470848",
"pm_score": 0,
"selected": false,
"text": "#Adjust it to the size you want. Ignore the from bit.\nexport CATALINA_OPTS=\"-Xmx1024m\"\n#This should point to your catalina base directory \nexport CATALINA_BASE=/usr/local/tomcat\n#This is only used if you editing the instance of your tomcat\n/usr/share/tomcat6/bin/startup.sh\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1282409/"
] |
286,021
|
<p>We have YouTube videos on a site and want to detect if it is likely that they will not be able to view them due to (mostly likely) company policy or otherwise.</p>
<p>We have two sites:</p>
<p>1) Flex / Flash
2) HTML</p>
<p>I think with Flex I can attempt to download <a href="http://youtube.com/crossdomain.xml" rel="noreferrer">http://youtube.com/crossdomain.xml</a> and if it is valid XML assume the site is available</p>
<p>But with HTML I don't know how to do it. I can't even think of a 'nice hack'.</p>
|
[
{
"answer_id": 286055,
"author": "Tristan Havelick",
"author_id": 30529,
"author_profile": "https://Stackoverflow.com/users/30529",
"pm_score": 3,
"selected": false,
"text": "<html>\n\n<head>\n <script src=\"http://www.youtube.com/js/account.js\"></script>\n <script>\n function has_you_tube()\n {\n if(typeof addVideosToQuicklist == 'function')\n {\n return true;\n }\n else\n {\n return false;\n }\n\n }\n </script>\n\n</head>\n<body>\n <script>alert( \"has_youtube: \" + has_you_tube() ); </script>\n</body>\n\n\n</html>\n"
},
{
"answer_id": 286066,
"author": "lacker",
"author_id": 2652,
"author_profile": "https://Stackoverflow.com/users/2652",
"pm_score": 4,
"selected": false,
"text": "var image = new Image();\nimage.src = \"http://youtube.com/favicon.ico\";\nif (image.height > 0) {\n // The user can access youtube\n} else {\n // The user can't access youtube\n}\n"
},
{
"answer_id": 1804634,
"author": "tiangolo",
"author_id": 219530,
"author_profile": "https://Stackoverflow.com/users/219530",
"pm_score": 5,
"selected": true,
"text": "var image = new Image();\nimage.onload = function(){\n// The user can access youtube\n};\nimage.onerror = function(){\n// The user can't access youtube\n};\nimage.src = \"http://youtube.com/favicon.ico\";\n"
},
{
"answer_id": 19913153,
"author": "mdogggg",
"author_id": 2094986,
"author_profile": "https://Stackoverflow.com/users/2094986",
"pm_score": 1,
"selected": false,
"text": "<script> function YouTubeTester() { \n if (player == undefined) {\n alert(\"youtube blocked\");\n }\n }\n</script>\n<script>window.setTimeout(\"YouTubeTester()\", 500);</script>\n"
},
{
"answer_id": 32099792,
"author": "Muyiwa Familoni",
"author_id": 5244102,
"author_profile": "https://Stackoverflow.com/users/5244102",
"pm_score": 0,
"selected": false,
"text": "<?php\n\n$v = file_get_contents(\"https://www.youtube.com/iframe_api\");\n\n//Tie counts to a variable\n$test = substr_count($v, 'loading');\n\nif ($test > 0)\n\n{ ?>\n <iframe>YOUTUBE VIDEO GOES HERE</iframe>\n\n <?php\n}\n\nelse\n\n{\n\necho \"<br/> no connection\";\n\n}\n\n?>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940/"
] |
286,031
|
<p>I am trying to share DTO's from my datalayer assembly between the client and WCF service. This works using svcutil, but doesn't work when using VS2008. VS2008 generates it's own DTO objects whereas svcutil uses the shared data type.</p>
<p>The svcutil parameters I used are:</p>
<pre><code>"C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\SvcUtil"
/serializer:DataContractSerializer
/language:vb
/out:ServiceClient.cs
/namespace:*,CommonWCF
/noconfig
/reference:"D:\trunk\DataLayer\bin\Debug\DataLayer.dll"
/collectionType:System.Collections.Generic.List`1
http://localhost:3371/Common.svc
</code></pre>
<p>I read that VS2008 just calls svcutil behind the scenes, so why doesn't it work? I really want to avoid adding a manual process to the build process.</p>
|
[
{
"answer_id": 397970,
"author": "oefe",
"author_id": 49793,
"author_profile": "https://Stackoverflow.com/users/49793",
"pm_score": 2,
"selected": false,
"text": "ClientFactory<T>"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24681/"
] |
286,039
|
<p>Is there a way to get the count of rows in all tables in a MySQL database without running a <code>SELECT count()</code> on each table?</p>
|
[
{
"answer_id": 286047,
"author": "gpojd",
"author_id": 28071,
"author_profile": "https://Stackoverflow.com/users/28071",
"pm_score": 8,
"selected": false,
"text": "SELECT table_name, table_rows\nFROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_SCHEMA = '**YOUR SCHEMA**';\n"
},
{
"answer_id": 286048,
"author": "Hates_",
"author_id": 3410,
"author_profile": "https://Stackoverflow.com/users/3410",
"pm_score": 10,
"selected": true,
"text": "SELECT SUM(TABLE_ROWS) \n FROM INFORMATION_SCHEMA.TABLES \n WHERE TABLE_SCHEMA = '{your_db}';\n"
},
{
"answer_id": 5477237,
"author": "Jake Drew",
"author_id": 682656,
"author_profile": "https://Stackoverflow.com/users/682656",
"pm_score": 4,
"selected": false,
"text": "CALL `COUNT_ALL_RECORDS_BY_TABLE` ();\n DELIMITER $$\n\nCREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `COUNT_ALL_RECORDS_BY_TABLE`()\nBEGIN\nDECLARE done INT DEFAULT 0;\nDECLARE TNAME CHAR(255);\n\nDECLARE table_names CURSOR for \n SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE();\n\nDECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;\n\nOPEN table_names; \n\nDROP TABLE IF EXISTS TCOUNTS;\nCREATE TEMPORARY TABLE TCOUNTS \n (\n TABLE_NAME CHAR(255),\n RECORD_COUNT INT\n ) ENGINE = MEMORY; \n\n\nWHILE done = 0 DO\n\n FETCH NEXT FROM table_names INTO TNAME;\n\n IF done = 0 THEN\n SET @SQL_TXT = CONCAT(\"INSERT INTO TCOUNTS(SELECT '\" , TNAME , \"' AS TABLE_NAME, COUNT(*) AS RECORD_COUNT FROM \", TNAME, \")\");\n\n PREPARE stmt_name FROM @SQL_TXT;\n EXECUTE stmt_name;\n DEALLOCATE PREPARE stmt_name; \n END IF;\n\nEND WHILE;\n\nCLOSE table_names;\n\nSELECT * FROM TCOUNTS;\n\nSELECT SUM(RECORD_COUNT) AS TOTAL_DATABASE_RECORD_CT FROM TCOUNTS;\n\nEND\n"
},
{
"answer_id": 8078817,
"author": "Robin Manoli",
"author_id": 942621,
"author_profile": "https://Stackoverflow.com/users/942621",
"pm_score": 2,
"selected": false,
"text": "SELECT TABLE_NAME, TABLE_ROWS\nFROM `TABLES`\nWHERE `TABLE_ROWS` >=0\n"
},
{
"answer_id": 8163665,
"author": "Michael Voigt",
"author_id": 716725,
"author_profile": "https://Stackoverflow.com/users/716725",
"pm_score": -1,
"selected": false,
"text": "$> gem install dbi\n$> gem install dbd-mysql\n require 'rubygems'\nrequire 'dbi'\n\ndb_handler = DBI.connect('DBI:Mysql:database_name:localhost', 'username', 'password')\n\n# Collect all Tables\nsql_1 = db_handler.prepare('SHOW tables;')\nsql_1.execute\ntables = sql_1.map { |row| row[0]}\nsql_1.finish\n\ntables.each do |table_name|\n sql_2 = db_handler.prepare(\"SELECT count(*) FROM #{table_name};\")\n sql_2.execute\n sql_2.each do |row|\n puts \"Table #{table_name} has #{row[0]} rows.\"\n end\n sql_2.finish\nend\n\ndb_handler.disconnect\n $> ruby count_table_records.rb\n Table users has 7328974 rows.\n"
},
{
"answer_id": 8690288,
"author": "Nathan",
"author_id": 71650,
"author_profile": "https://Stackoverflow.com/users/71650",
"pm_score": 7,
"selected": false,
"text": "SELECT CONCAT(\n 'SELECT \"', \n table_name, \n '\" AS table_name, COUNT(*) AS exact_row_count FROM `', \n table_schema,\n '`.`',\n table_name, \n '` UNION '\n) \nFROM INFORMATION_SCHEMA.TABLES \nWHERE table_schema = '**my_schema**';\n SELECT \"func\" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.func UNION \nSELECT \"general_log\" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.general_log UNION \nSELECT \"help_category\" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.help_category UNION \nSELECT \"help_keyword\" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.help_keyword UNION \nSELECT \"help_relation\" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.help_relation UNION \nSELECT \"help_topic\" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.help_topic UNION \nSELECT \"host\" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.host UNION \nSELECT \"ndb_binlog_index\" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.ndb_binlog_index UNION \n +------------------+-----------------+\n| table_name | exact_row_count |\n+------------------+-----------------+\n| func | 0 |\n| general_log | 0 |\n| help_category | 37 |\n| help_keyword | 450 |\n| help_relation | 990 |\n| help_topic | 504 |\n| host | 0 |\n| ndb_binlog_index | 0 |\n+------------------+-----------------+\n8 rows in set (0.01 sec)\n"
},
{
"answer_id": 10009253,
"author": "koswara1482",
"author_id": 1312571,
"author_profile": "https://Stackoverflow.com/users/1312571",
"pm_score": 0,
"selected": false,
"text": "$dtb = mysql_query(\"SHOW TABLES\") or die (mysql_error());\n$jmltbl = 0;\n$jml_record = 0;\n$jml_record = 0;\n\nwhile ($row = mysql_fetch_array($dtb)) { \n $sql1 = mysql_query(\"SELECT * FROM \" . $row[0]); \n $jml_record = mysql_num_rows($sql1); \n echo \"Table: \" . $row[0] . \": \" . $jml_record record . \"<br>\"; \n $jmltbl++;\n $jml_record += $jml_record;\n}\n\necho \"--------------------------------<br>$jmltbl Tables, $jml_record > records.\";\n"
},
{
"answer_id": 11778602,
"author": "Gustavo Castro",
"author_id": 1571560,
"author_profile": "https://Stackoverflow.com/users/1571560",
"pm_score": 4,
"selected": false,
"text": " SELECT TABLE_NAME,SUM(TABLE_ROWS) \n FROM INFORMATION_SCHEMA.TABLES \n WHERE TABLE_SCHEMA = 'your_db' \n GROUP BY TABLE_NAME;\n"
},
{
"answer_id": 11803106,
"author": "user1575139",
"author_id": 1575139,
"author_profile": "https://Stackoverflow.com/users/1575139",
"pm_score": 1,
"selected": false,
"text": "select concat('select \"', table_schema, '.', table_name, '\" as `schema.table`,\n count(*)\n from ', table_schema, '.', table_name, ' union ') as 'Query Row'\n from information_schema.tables\n union\n select '(select null, null limit 0);';\n"
},
{
"answer_id": 17820410,
"author": "djburdick",
"author_id": 181585,
"author_profile": "https://Stackoverflow.com/users/181585",
"pm_score": 6,
"selected": false,
"text": "show table status;\n"
},
{
"answer_id": 21794208,
"author": "Nimesh07",
"author_id": 2524176,
"author_profile": "https://Stackoverflow.com/users/2524176",
"pm_score": 2,
"selected": false,
"text": "SELECT IFNULL(table_schema,'Total') \"Database\",TableCount \nFROM (SELECT COUNT(1) TableCount,table_schema \n FROM information_schema.tables \n WHERE table_schema NOT IN ('information_schema','mysql') \n GROUP BY table_schema WITH ROLLUP) A;\n"
},
{
"answer_id": 22483503,
"author": "lsaffie",
"author_id": 1161661,
"author_profile": "https://Stackoverflow.com/users/1161661",
"pm_score": 1,
"selected": false,
"text": "mysql -uroot -p mydb -e \"show tables\"\n array=( table1 table2 table3 )\n\nfor i in \"${array[@]}\"\ndo\n echo $i\n mysql -uroot mydb -e \"select count(*) from $i\"\ndone\n chmod +x script.sh; ./script.sh\n"
},
{
"answer_id": 25373966,
"author": "apotek",
"author_id": 1499866,
"author_profile": "https://Stackoverflow.com/users/1499866",
"pm_score": 0,
"selected": false,
"text": "# Put this function in your bash and call with:\n# rowpicker DBUSER DBPASS DBNAME [TABLEPATTERN]\nfunction rowpicker() {\n UN=$1\n PW=$2\n DB=$3\n if [ ! -z \"$4\" ]; then\n PAT=\"LIKE '$4'\"\n tot=-2\n else\n PAT=\"\"\n tot=-1\n fi\n for t in `mysql -u \"$UN\" -p\"$PW\" \"$DB\" -e \"SHOW TABLES $PAT\"`;do\n if [ $tot -lt 0 ]; then\n echo \"Skipping $t\";\n let \"tot += 1\";\n else\n c=`mysql -u \"$UN\" -p\"$PW\" \"$DB\" -e \"SELECT count(*) FROM $t\"`;\n c=`echo $c | cut -d \" \" -f 2`;\n echo \"$t: $c\";\n let \"tot += c\";\n fi;\n done;\n echo \"total rows: $tot\"\n}\n"
},
{
"answer_id": 29371708,
"author": "AdamMc331",
"author_id": 3131147,
"author_profile": "https://Stackoverflow.com/users/3131147",
"pm_score": -1,
"selected": false,
"text": "COUNT(distinct [column]) SELECT \n COUNT(distinct t1.id) + \n COUNT(distinct t2.id) + \n COUNT(distinct t3.id) AS totalRows\nFROM firstTable t1, secondTable t2, thirdTable t3;\n"
},
{
"answer_id": 40461844,
"author": "filimonov",
"author_id": 1555175,
"author_profile": "https://Stackoverflow.com/users/1555175",
"pm_score": 2,
"selected": false,
"text": "SET @table_schema = DATABASE();\n-- or SET @table_schema = 'my_db_name';\n\nSET GROUP_CONCAT_MAX_LEN=131072;\nSET @selects = NULL;\n\nSELECT GROUP_CONCAT(\n 'SELECT \"', table_name,'\" as TABLE_NAME, COUNT(*) as TABLE_ROWS FROM `', table_name, '`'\n SEPARATOR '\\nUNION\\n') INTO @selects\n FROM information_schema.TABLES\n WHERE TABLE_SCHEMA = @table_schema\n AND ENGINE = 'InnoDB'\n AND TABLE_TYPE = \"BASE TABLE\";\n\nSELECT CONCAT_WS('\\nUNION\\n',\n CONCAT('SELECT TABLE_NAME, TABLE_ROWS FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND ENGINE <> \"InnoDB\" AND TABLE_TYPE = \"BASE TABLE\"'),\n @selects) INTO @selects;\n\nPREPARE stmt FROM @selects;\nEXECUTE stmt USING @table_schema;\nDEALLOCATE PREPARE stmt;\n"
},
{
"answer_id": 40805736,
"author": "user3260912",
"author_id": 3260912,
"author_profile": "https://Stackoverflow.com/users/3260912",
"pm_score": 3,
"selected": false,
"text": "SELECT\ntable_schema 'Database',\nSUM(data_length + index_length) AS 'DBSize',\nSUM(TABLE_ROWS) AS DBRows,\nSUM(AUTO_INCREMENT) AS DBAutoIncCount\nFROM information_schema.tables\nGROUP BY table_schema;\n\n\n+--------------------+-----------+---------+----------------+\n| Database | DBSize | DBRows | DBAutoIncCount |\n+--------------------+-----------+---------+----------------+\n| Core | 35241984 | 76057 | 8341 |\n| information_schema | 163840 | NULL | NULL |\n| jspServ | 49152 | 11 | 856 |\n| mysql | 7069265 | 30023 | 1 |\n| net_snmp | 47415296 | 95123 | 324 |\n| performance_schema | 0 | 1395326 | NULL |\n| sys | 16384 | 6 | NULL |\n| WebCal | 655360 | 2809 | NULL |\n| WxObs | 494256128 | 530533 | 3066752 |\n+--------------------+-----------+---------+----------------+\n9 rows in set (0.40 sec)\n SELECT\ntable_schema 'Database',\nSUM(data_length + index_length) AS 'DBSize',\nGREATEST(SUM(TABLE_ROWS), SUM(AUTO_INCREMENT)) AS DBRows\nFROM information_schema.tables\nGROUP BY table_schema;\n"
},
{
"answer_id": 56710008,
"author": "Eduardo Cuomo",
"author_id": 717267,
"author_profile": "https://Stackoverflow.com/users/717267",
"pm_score": 5,
"selected": false,
"text": "SELECT\n TABLE_NAME, SUM(TABLE_ROWS)\nFROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_SCHEMA = '{Your_DB}'\nGROUP BY TABLE_NAME;\n +----------------+-----------------+\n| TABLE_NAME | SUM(TABLE_ROWS) |\n+----------------+-----------------+\n| calls | 7533 |\n| courses | 179 |\n| course_modules | 298 |\n| departments | 58 |\n| faculties | 236 |\n| modules | 169 |\n| searches | 25423 |\n| sections | 532 |\n| universities | 57 |\n| users | 10293 |\n+----------------+-----------------+\n"
},
{
"answer_id": 57100657,
"author": "Adam",
"author_id": 209568,
"author_profile": "https://Stackoverflow.com/users/209568",
"pm_score": 0,
"selected": false,
"text": "select CONCAT( 'select * from (\\n', group_concat( single_select SEPARATOR ' UNION\\n'), '\\n ) Q order by Q.exact_row_count desc') as sql_query\nfrom (\n SELECT CONCAT(\n 'SELECT \"', \n table_name, \n '\" AS table_name, COUNT(1) AS exact_row_count\n FROM `', \n table_schema,\n '`.`',\n table_name, \n '`'\n ) as single_select\n FROM INFORMATION_SCHEMA.TABLES \n WHERE table_schema = 'YOUR_SCHEMA_NAME'\n and table_type = 'BASE TABLE'\n) Q \n group_concat_max_len"
},
{
"answer_id": 61436094,
"author": "vast",
"author_id": 1617079,
"author_profile": "https://Stackoverflow.com/users/1617079",
"pm_score": -1,
"selected": false,
"text": "SELECT \nconcat('select ''', table_name ,''' as TableName, COUNT(*) as RowCount from ' , table_name , ' UNION ALL ') as TR FROM\ninformation_schema.tables where \ntable_schema = 'Database Name'\n"
},
{
"answer_id": 72717988,
"author": "Jay",
"author_id": 11109901,
"author_profile": "https://Stackoverflow.com/users/11109901",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n\nreadarray -t TABLES < <(mysql --skip-column-names -u myuser -pmypassword mydbname -e \"show tables\")\n\n# now we have an array like:\n# TABLES='([0]=\"customer\" [1]=\"order\" [2]=\"product\")'\n# You can print out the array with:\n#declare -p TABLES\n\n\nfor i in \"${TABLES[@]}\"\ndo\n #echo $i\n COUNT=$(mysql --skip-column-names -u username -pmypassword mydbname -e \"select count(*) from $i\")\n echo $i : $COUNT\ndone\n"
},
{
"answer_id": 73653042,
"author": "HoldOffHunger",
"author_id": 2430549,
"author_profile": "https://Stackoverflow.com/users/2430549",
"pm_score": 0,
"selected": false,
"text": "INFORMATION_SCHEMA count() SET SESSION group_concat_max_len = 1000000;\n SELECT CONCAT('SELECT ', GROUP_CONCAT(table1.count SEPARATOR ',\\n')) FROM (\n SELECT concat('(SELECT count(id) AS \\'',table_name,' Count\\' ','FROM ',table_name,') AS ',table_name,'_Count') AS 'count'\n FROM information_schema.tables \n WHERE table_schema = '**YOUR_DATABASE_HERE**'\n) AS table1\n SELECT (SELECT count(id) AS 'table1 Count' FROM table1) AS table1_Count,\n (SELECT count(id) AS 'table2 Count' FROM table2) AS table2_Count,\n (SELECT count(id) AS 'table3 Count' FROM table3) AS table3_Count;\n *************************** 1. row ***************************\ntable1_Count: 1\ntable2_Count: 1\ntable3_Count: 0\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37204/"
] |
286,058
|
<p>If I have a key set of 1000, what is a suitable size for my Hash table, and how is that determined?</p>
|
[
{
"answer_id": 286063,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 1,
"selected": false,
"text": "Hashtable"
},
{
"answer_id": 286079,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 4,
"selected": true,
"text": "Hashtable(int initialCapacity, float loadFactor) \n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36545/"
] |
286,060
|
<p>ASP.Net 3.5 running under IIS 7 doesn't seem to allow this out of the box.</p>
<pre><code> if (!EventLog.SourceExists("MyAppLog"))
EventLog.CreateEventSource("MyAppLog", "Application");
EventLog myLog = new EventLog();
myLog.Source = "MyAppLog";
myLog.WriteEntry("Message");
</code></pre>
|
[
{
"answer_id": 7848414,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 5,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\eventlog\\Application\\MY-AWESOME-APP EventMessageFile EventLog.CreateEventSource"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25372/"
] |
286,061
|
<p>I seem to be losing a lot of precision with floats.</p>
<p>For example I need to solve a matrix:</p>
<pre><code>4.0x -2.0y 1.0z =11.0
1.0x +5.0y -3.0z =-6.0
2.0x +2.0y +5.0z =7.0
</code></pre>
<p>This is the code I use to import the matrix from a text file:</p>
<pre><code>f = open('gauss.dat')
lines = f.readlines()
f.close()
j=0
for line in lines:
bits = string.split(line, ',')
s=[]
for i in range(len(bits)):
if (i!= len(bits)-1):
s.append(float(bits[i]))
#print s[i]
b.append(s)
y.append(float(bits[len(bits)-1]))
</code></pre>
<p>I need to solve using gauss-seidel so I need to rearrange the equations for x, y, and z:</p>
<pre><code>x=(11+2y-1z)/4
y=(-6-x+3z)/5
z=(7-2x-2y)/7
</code></pre>
<p>Here is the code I use to rearrange the equations. <code>b</code> is a matrix of coefficients and <code>y</code> is the answer vector:</p>
<pre><code>def equations(b,y):
i=0
eqn=[]
row=[]
while(i<len(b)):
j=0
row=[]
while(j<len(b)):
if(i==j):
row.append(y[i]/b[i][i])
else:
row.append(-b[i][j]/b[i][i])
j=j+1
eqn.append(row)
i=i+1
return eqn
</code></pre>
<p>However the answers I get back aren't precise to the decimal place.</p>
<p>For example, upon rearranging the second equation from above, I should get:</p>
<pre><code>y=-1.2-.2x+.6z
</code></pre>
<p>What I get is:</p>
<pre><code>y=-1.2-0.20000000000000001x+0.59999999999999998z
</code></pre>
<p>This might not seem like a big issue but when you raise the number to a very high power the error is quite large. Is there a way around this? I tried the <code>Decimal</code> class but it does not work well with powers (i.e, <code>Decimal(x)**2</code>).</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 286064,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 5,
"selected": true,
"text": "EDIT: >>> import decimal\n>>> print(decimal.Decimal(\"1.2\") ** 2)\n1.44\n decimal.Decimal"
},
{
"answer_id": 286119,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "b = [\n [4.0, -2.0, 1.0],\n [1.0, +5.0, -3.0],\n [2.0, +2.0, +5.0],\n]\ny = [ 11.0, -6.0, 7.0 ]\n >>> a\n0.20000000000000001\n>>> \"%.4f\" % (a,)\n'0.2000'\n"
},
{
"answer_id": 287079,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "def read_matrix(f):\n b,y = [], []\n for line in f:\n bits = line.split(\",\")\n b.append( map(gmpy.mpq, bits[:-1]) )\n y.append(gmpy.mpq(bits[-1]))\n return b,y\n"
},
{
"answer_id": 317171,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/env python\nfrom numpy import abs, dot, loadtxt, max\nfrom numpy.linalg import solve\n\ndata = loadtxt('gauss.dat', delimiter=',')\na, b = data[:,:-1], data[:,-1:]\nx = solve(a, b) # here you may use any method you like instead of `solve`\nprint(x)\nprint(max(abs((dot(a, x) - b) / b))) # check solution\n $ cat gauss.dat\n4.0, 2.0, 1.0, 11.0\n1.0, 5.0, 3.0, 6.0 \n2.0, 2.0, 5.0, 7.0\n\n$ python loadtxt_example.py\n[[ 2.4]\n [ 0.6]\n [ 0.2]]\n0.0\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338360/"
] |
286,062
|
<p>How would I go about creating a Google map that allows the user to zoom beyond the default zoom levels for the map? Would I have to create a new map type that has a greater maximum zoom? Are there any tutorials out there that show how to do this?</p>
|
[
{
"answer_id": 286064,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 5,
"selected": true,
"text": "EDIT: >>> import decimal\n>>> print(decimal.Decimal(\"1.2\") ** 2)\n1.44\n decimal.Decimal"
},
{
"answer_id": 286119,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "b = [\n [4.0, -2.0, 1.0],\n [1.0, +5.0, -3.0],\n [2.0, +2.0, +5.0],\n]\ny = [ 11.0, -6.0, 7.0 ]\n >>> a\n0.20000000000000001\n>>> \"%.4f\" % (a,)\n'0.2000'\n"
},
{
"answer_id": 287079,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "def read_matrix(f):\n b,y = [], []\n for line in f:\n bits = line.split(\",\")\n b.append( map(gmpy.mpq, bits[:-1]) )\n y.append(gmpy.mpq(bits[-1]))\n return b,y\n"
},
{
"answer_id": 317171,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/env python\nfrom numpy import abs, dot, loadtxt, max\nfrom numpy.linalg import solve\n\ndata = loadtxt('gauss.dat', delimiter=',')\na, b = data[:,:-1], data[:,-1:]\nx = solve(a, b) # here you may use any method you like instead of `solve`\nprint(x)\nprint(max(abs((dot(a, x) - b) / b))) # check solution\n $ cat gauss.dat\n4.0, 2.0, 1.0, 11.0\n1.0, 5.0, 3.0, 6.0 \n2.0, 2.0, 5.0, 7.0\n\n$ python loadtxt_example.py\n[[ 2.4]\n [ 0.6]\n [ 0.2]]\n0.0\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
286,076
|
<p>My question is a lot like <a href="https://stackoverflow.com/questions/80721/">this one</a>. However I'm on MySQL and I'm looking for the "lowest tech" solution that I can find. </p>
<p>The situation is that I have 2 databases that should have the same data in them but they are updated primarily when they are not able to contact each other. I suspect that there is some sort of clustering or master/slave thing that would be able to sync them just fine. However in my cases that is major overkill as this is just a scratch DB for my own use.</p>
<p>What is a good way to do this?</p>
<p>My current approach is to have a Federated table on one of them and, every so often, stuff the data over the wire to the other with an insert/select. It get a bit convoluted trying to deal with primary keys and what not. (<code>insert ignore</code> seems to not work correctly)</p>
<p>p.s. I can easily build a query that selects the rows to transfer.</p>
|
[
{
"answer_id": 288523,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 1,
"selected": true,
"text": "INSERT...SELECT...ON DUPLICATE UPDATE"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
286,081
|
<p>When I access a wrong call to a sql server data into my application in classical ASP I get this message in my entire site: Service Unavailable. It stopped. My site is in a remote host. Don´t know what to do. What can I tell to the "support team" of them to fix that?</p>
|
[
{
"answer_id": 286292,
"author": "Cyril Gupta",
"author_id": 33052,
"author_profile": "https://Stackoverflow.com/users/33052",
"pm_score": 1,
"selected": false,
"text": "Run IIS\nRight click on the node 'Application Pools' in your left sidebar.\nClick on the tab 'Health'\nRemove the check on 'Enable Rapid Fail Protection' \n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22869/"
] |
286,085
|
<p>I've installed Subversion on Ubuntu following the guide <em><a href="http://alephzarro.com/blog/2007/01/07/installation-of-subversion-on-ubuntu-with-apache-ssl-and-basicauth" rel="nofollow noreferrer">Installation of Subversion on Ubuntu, with Apache, SSL, and BasicAuth.</a></em>.</p>
<p>It works, and I was able commit and create different repositories, but somehow, from time to time (sometimes minutes), when trying to do a commit, I'm forced to reset or recreate my user and password with the following command.</p>
<pre><code>htpasswd2 -c -m /etc/apache2/dav_svn.passwd $AUTH_USER
</code></pre>
<p>Because SVN does not recognize my user/password anymore. </p>
<p>I'm using TortoiseSVN as SVN Client. I would like to know why this is happening. Maybe it's a configuration issue, or maybe TortoiseSVN is sending invalid credentials, causing a locked account. Since I'm far from being an SVN expert/administrator. Are there some pointers in order to attack the problem.</p>
|
[
{
"answer_id": 286127,
"author": "ala",
"author_id": 37198,
"author_profile": "https://Stackoverflow.com/users/37198",
"pm_score": -1,
"selected": false,
"text": "<domain>\\<user>"
},
{
"answer_id": 293726,
"author": "tommym",
"author_id": 37607,
"author_profile": "https://Stackoverflow.com/users/37607",
"pm_score": 2,
"selected": true,
"text": "md5 /etc/apache2/dav_svn.passwd cat /etc/apache2/dav_svn.passwd touch /etc/apache2/dav_svn.passwd chmod 644 /etc/apache2/dav_svn.passwd"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32424/"
] |
286,090
|
<p>The question is actually about stack overflows in C.
I have an assigment that I can not get done for the life of me, I've looked at everything in the gdb and I just cant figure it.</p>
<p>The question is the following:</p>
<pre><code>int i,n;
void confused()
{
printf("who called me");
exit(0);
}
void shell_call(char *c)
{
printf(" ***Now calling \"%s\" shell command *** \n",c);
system(c);
exit(0);
}
void victim_func()
{
int a[4];
printf("[8]:%x\n", &a[8]);
printf("Enter n: "); scanf("%d",&n);
printf("Enter %d HEX Values \n",n);
for(i=0;i<n;i++) scanf("%x",&a[i]);
printf("Done reading junk numbers\n");
}
int main()
{
printf("ls=736c --- ps = 7370 --- cal = 6c6163\n");
printf("location of confused %x \n", confused);
printf("location of shell_call %x \n", shell_call);
victim_func();
printf("Done, thank you\n");
}
</code></pre>
<p>Ok, so I managed to get the first question correctly, which is to arbitrarily call one of the two functions not explicitly called in the main path. By the way, this has to be done while running the program without any modifications.
I did this by running the program, setting <code>N</code> to <code>7</code>, which gets me to the Function Pointer of the <code>victim_func</code> frame, I write <code>a[7]</code> with the memory address of confused or <code>shell_call</code>, and it works. (I have a 64 bit machine, thats why I have to get it to 7, since the EBI pointer is 2 ints wide, instead of 1)</p>
<p>My question is the following, how could I control which argument gets passed to the <code>shell_code</code> funcion? ie. how do I write a <code>string</code> to <code>char* c</code>.
The whole point is executing unix commands like <strong>ps</strong> etc, by running only the program.</p>
<p>I figured writing the EBI pointer with the hex representation of <strong>ps</strong> and setting the arg list of <code>shell_call</code> to that, but that didn't work. I also tried inputing <code>argsv</code> arguments and setting the arg list of <code>shell_call</code> to the <code>arg_list</code> of main, but didn't work either. </p>
<p>I think the second version should work, but I believe I'm not setting the arg list of the new stack frame correctly ( I did it by writing <code>a[8]</code> to <code>0</code>, since its the first part of the function pointer, and writing <code>a[9]=736c</code> and <code>a[10]=0000</code>, but its probably not right since those are the parameters of <code>victim_func</code>. So how do I access the parameters of <code>shell_call</code>? </p>
|
[
{
"answer_id": 292514,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 1,
"selected": false,
"text": "main() shell_call() victim_func() leave"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
286,091
|
<p>I am not a fan of using SQL*PLUS as an interface to Oracle. I usually use <a href="http://sourceforge.net/projects/yasql/" rel="noreferrer">yasql</a>, but it hasn't been updated since 2005 and can do with some improvements. A quick <a href="http://www.google.com/search?q=sql*plus+replacement" rel="noreferrer">Google search</a> shows yasql and <a href="http://www.sqlpal.com/" rel="noreferrer">SQLPal</a>. I am using linux, so SQLPal is not an option. </p>
<p>Are there any alternatives out there, or am I stuck with an interface that I do not like or one that is no longer maintained? </p>
|
[
{
"answer_id": 7433988,
"author": "Николай Мишин",
"author_id": 937070,
"author_profile": "https://Stackoverflow.com/users/937070",
"pm_score": 1,
"selected": false,
"text": "alias sqr='sqlsh -d DBI:Oracle:MYSERVER.COM -u USER -p PASSWORD'\n"
},
{
"answer_id": 54116222,
"author": "NinthTest",
"author_id": 2167747,
"author_profile": "https://Stackoverflow.com/users/2167747",
"pm_score": 0,
"selected": false,
"text": "function sqlplus {\n socat READLINE,history=$HOME/.sqlplus_history EXEC:\"$ORACLE_HOME/bin/sqlplus $(echo $@ | sed 's/\\([\\:]\\)/\\\\\\1/g')\",pty,setsid,ctty\n status=$?\n}\n cat /dev/null > $HOME/.sqlplus_history"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28071/"
] |
286,093
|
<p>I want to assert that a method is called exactly one time. I'm using RhinoMocks 3.5.</p>
<p>Here's what I thought would work:</p>
<pre class="lang-cs prettyprint-override"><code>[Test]
public void just_once()
{
var key = "id_of_something";
var source = MockRepository.GenerateStub<ISomeDataSource>();
source.Expect(x => x.GetSomethingThatTakesALotOfResources(key))
.Return(new Something())
.Repeat.Once();
var client = new Client(soure);
// the first call I expect the client to use the source
client.GetMeMyThing(key);
// the second call the result should be cached
// and source is not used
client.GetMeMyThing(key);
}
</code></pre>
<p>I want this test to fail if the second invocation of <code>GetMeMyThing()</code> calls <code>source.GetSomethingThatTakesALotOfResources()</code>.</p>
|
[
{
"answer_id": 286125,
"author": "Christopher Bennage",
"author_id": 6855,
"author_profile": "https://Stackoverflow.com/users/6855",
"pm_score": 2,
"selected": false,
"text": "[Test]\npublic void just_once()\n{\n var key = \"id_of_something\";\n\n var source = MockRepository.GenerateStub<ISomeDataSource>();\n\n // set a positive expectation\n source.Expect(x => x.GetSomethingThatTakesALotOfResources(key))\n .Return(new Something())\n .Repeat.Once();\n\n var client = new Client(soure);\n\n client.GetMeMyThing(key);\n\n // set a negative expectation\n source.Expect(x => x.GetSomethingThatTakesALotOfResources(key))\n .Return(new Something())\n .Repeat.Never();\n\n client.GetMeMyThing(key);\n}\n"
},
{
"answer_id": 568446,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 6,
"selected": true,
"text": "[Test]\npublic void just_once()\n{\n // Arrange (Important to GenerateMock not GenerateStub)\n var a = MockRepository.GenerateMock<ISomeDataSource>();\n a.Expect(x => x.GetSomethingThatTakesALotOfResources()).Return(new Something()).Repeat.Once();\n\n // Act\n // First invocation should call GetSomethingThatTakesALotOfResources\n a.GetMeMyThing();\n\n // Second invocation should return cached result\n a.GetMeMyThing();\n\n // Assert\n a.VerifyAllExpectations();\n}\n"
},
{
"answer_id": 886264,
"author": "Jon Cahill",
"author_id": 10830,
"author_profile": "https://Stackoverflow.com/users/10830",
"pm_score": 4,
"selected": false,
"text": " [Test]\n public void just_once()\n {\n var key = \"id_of_something\";\n\n var source = MockRepository.GenerateStub<ISomeDataSource>();\n\n // set a positive expectation\n source.Expect(x => x.GetSomethingThatTakesALotOfResources(key))\n .Return(new Something())\n .Repeat.Once();\n\n var client = new Client(soure);\n client.GetMeMyThing(key);\n client.GetMeMyThing(key);\n\n source.AssertWasCalled(x => x.GetSomethingThatTakesALotOfResources(key),\n x => x.Repeat.Once());\n source.VerifyAllExpectations();\n }\n"
},
{
"answer_id": 5188515,
"author": "Ergwun",
"author_id": 177018,
"author_profile": "https://Stackoverflow.com/users/177018",
"pm_score": 2,
"selected": false,
"text": "...\nuint callCount = 0;\nsource.Expect(x => x.GetSomethingThatTakesALotOfResources(key))\n .Return(new Something())\n .WhenCalled((y) => { callCount++; });\n...\nAssert.AreEqual(1, callCount);\n"
},
{
"answer_id": 47057979,
"author": "Balpreet Patil",
"author_id": 1351171,
"author_profile": "https://Stackoverflow.com/users/1351171",
"pm_score": 0,
"selected": false,
"text": "var mock = MockRepository.GenerateStrictMock<IMustOnlyBeCalledOnce>();\nmock.Expect(a => a.Process()).Repeat.Once();\nvar helloWorld= new HelloWorld(mock);\n\nhelloworld.Process()\n\nmock.VerifyAllExpectations();\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6855/"
] |
286,096
|
<pre><code>typedef struct {
nat id;
char *data;
} element_struct;
typedef element_struct * element;
void push(element e, queue s) {
nat lt = s->length;
if (lt == max_length - 1) {
printf("Error in push: Queue is full.\n");
return;
}
else {
s->contents[lt] = e;
s->length = lt + 1;
}
}
int main () {
push(something_of_type_element, s);
}
</code></pre>
<p>How would i go about formatting "<code>something_of_type_element</code>"?</p>
<p>Thanks</p>
<p>Notes:
nat is the same as int</p>
|
[
{
"answer_id": 286108,
"author": "David Norman",
"author_id": 34502,
"author_profile": "https://Stackoverflow.com/users/34502",
"pm_score": 2,
"selected": false,
"text": "element elem = malloc(sizeof(element_struct));\nif (elem == NULL) {\n /* Handle error. */\n}\n\nelem->id = something;\nelem->data = something_else;\n\npush(elem, s);\n"
},
{
"answer_id": 286111,
"author": "Judge Maygarden",
"author_id": 1491,
"author_profile": "https://Stackoverflow.com/users/1491",
"pm_score": 2,
"selected": true,
"text": "element_struct foo = { 1, \"bar\" };\npush(&foo, s);\n element_struct foo = {\n .id = 1,\n .data = \"bar\"\n};\npush(&foo, s);\n element_struct foo = malloc(sizeof (element_struct));\n\nfoo.id = 1;\nfoo.data = \"bar\";\npush(foo, s);\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31549/"
] |
286,103
|
<p>Our Windows Forms application by default saves data files in a user's 'My Documents' folder (on XP) or 'Documents' folder (on Vista). We look up this location by calling:</p>
<pre><code>Environment.GetFolderPath( Environment.SpecialFolder.Personal )
</code></pre>
<p>We know for sure this works great for users whose personal folder is on a local disk. What we're not sure about is domain users who have Folder Redirection in effect for their profile/personal data folders.</p>
<p>My question is: <strong>Does the above call properly resolve regardless of whether Folder Redirection is active?</strong></p>
<p>I don't have the environment to test this out, and I haven't been able to find any definite confirmation one way or the other.</p>
|
[
{
"answer_id": 286131,
"author": "Jon Norton",
"author_id": 4797,
"author_profile": "https://Stackoverflow.com/users/4797",
"pm_score": 1,
"selected": false,
"text": "Environment.GetFolderPath SHGetSpecialFolderPath"
},
{
"answer_id": 286147,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 3,
"selected": true,
"text": "\\HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\\\n"
},
{
"answer_id": 11563415,
"author": "rachel",
"author_id": 423306,
"author_profile": "https://Stackoverflow.com/users/423306",
"pm_score": 2,
"selected": false,
"text": "Environment.GetFolderPath(Environment.SpecialFolder.Personal) System.ArgumentException: Absolute path information is required.\n at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath)\n at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)\n at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String path)\n at System.Environment.GetFolderPath(SpecialFolder folder, SpecialFolderOption option)\n at System.Environment.GetFolderPath(SpecialFolder folder)\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17966/"
] |
286,104
|
<p>Before anybody asks, I am not doing any kind of screenscraping.</p>
<p>I'm trying to parse an html string to find a div with a certain id. I cannot for the life of me get this to work. The following expression worked in one instance, but not in another. I'm not sure if it has to do with extra elements in the html or not.</p>
<pre><code><div\s*?id=(\""|&quot;|&#34;)content(\""|&quot;|&#34;).*?>\s*?(?>(?! <div\s*?> | </div> ) | <div\s*?>(?<DEPTH>) | </div>(?<-DEPTH>) | .?)*(?(DEPTH)(?!))</div>
</code></pre>
<p>It is finding the first div with the right id correctly, but it then closes at the first closing div, and not the related div.</p>
<pre><code><div id="firstdiv">begining content<div id="content">some other stuff
<div id="otherdiv">other stuff here</div>
more stuff
</div>
</div>
</code></pre>
<p>This should bring back</p>
<pre><code><div id="content">some other stuff
<div id="otherdiv">other stuff here</div>
more stuff
</div>
</code></pre>
<p>, but for some reason, it is not. It is bring back:</p>
<pre><code> <div id="content">some other stuff
<div id="otherdiv">other stuff here</div>
</code></pre>
<p>Does anybody have an easier expression to handle this?</p>
<p>To clarify, this is in .NET, and I'm using the DEPTH keyword. You can find more details <a href="http://www.m-8.dk/resources/RegEx-Balancing-Group.aspx" rel="noreferrer">here</a>.</p>
|
[
{
"answer_id": 287758,
"author": "pro3carp3",
"author_id": 7899,
"author_profile": "https://Stackoverflow.com/users/7899",
"pm_score": 4,
"selected": true,
"text": "(?<text>\n(<div\\s*?id=(\\\"|"|&\\#34;)content(\\\"|"|&\\#34;).*?>)\n\n (?>\n .*?</div>\n |\n .*?<div (?>depth)\n |\n .*?</div> (?>-depth)\n )*)\n (?(depth)(?!))\n.*?</div>\n using System;\nusing System.Text.RegularExpressions;\n\nnamespace Temp\n{\n class Program\n {\n static void Main()\n {\n string s = @\"\n<div id=\"\"firstdiv\"\">begining content<div id=\"\"content\"\">some other stuff\n <div id=\"\"otherdiv\"\">other stuff here</div>\n more stuff\n </div>\n</div>\";\n Regex r = new Regex(@\"(?<text>(<div\\s*?id=(\\\"\"|"|&\\#34;)\"\n + @\"content(\\\"\"|"|&\\#34;).*?>)(?>.*?</div>|.*?<div \"\n + @\"(?>depth)|.*?</div> (?>-depth))*)(?(depth)(?!)).*?</div>\",\n RegexOptions.Singleline);\n Console.WriteLine(\"HTML:\\n\");\n Console.WriteLine(s);\n Match m = r.Match(s);\n if (m.Success)\n {\n Console.WriteLine(\"\\nCaptured text:\\n\");\n Console.WriteLine(m.Groups[4]);\n\n }\n Console.ReadLine();\n }\n }\n}\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8534/"
] |
286,105
|
<p>I have a C library with numerous math routines for dealing with vectors, matrices, quaternions and so on. It needs to remain in C because I often use it for embedded work and as a Lua extension. In addition, I have C++ class wrappers to allow for more convenient object management and operator overloading for math operations using the C API. The wrapper only consists of a header file and as much use on inlining is made as possible.</p>
<p>Is there an appreciable penalty for wrapping the C code versus porting and inlining the implementation directly into the C++ class? This library is used in time critical applications. So, does the boost from eliminating indirection compensate for the maintenance headache of two ports?</p>
<p>Example of C interface:</p>
<pre><code>typedef float VECTOR3[3];
void v3_add(VECTOR3 *out, VECTOR3 lhs, VECTOR3 rhs);
</code></pre>
<p>Example of C++ wrapper:</p>
<pre><code>class Vector3
{
private:
VECTOR3 v_;
public:
// copy constructors, etc...
Vector3& operator+=(const Vector3& rhs)
{
v3_add(&this->v_, this->v_, const_cast<VECTOR3> (rhs.v_));
return *this;
}
Vector3 operator+(const Vector3& rhs) const
{
Vector3 tmp(*this);
tmp += rhs;
return tmp;
}
// more methods...
};
</code></pre>
|
[
{
"answer_id": 286143,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 2,
"selected": false,
"text": "-S -save-temps"
},
{
"answer_id": 286617,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 3,
"selected": true,
"text": "// V3impl.inl\nvoid V3DECL v3_add(VECTOR3 *out, VECTOR3 lhs, VECTOR3 rhs)\n{\n // here you maintain the actual implementations\n // ...\n}\n\n// C header\n#define V3DECL \nvoid V3DECL v3_add(VECTOR3 *out, VECTOR3 lhs, VECTOR3 rhs);\n\n// C body\n#include \"V3impl.inl\"\n\n\n// CPP Header\n#define V3DECL inline\nnamespace v3core {\n #include \"V3impl.inl\"\n} // namespace\n\nclass Vector3D { ... }\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1491/"
] |
286,117
|
<p>I work on a team with about 10 developers. Some of the developers have very exacting formatting needs. I would like to find a pretty printer that I could configure to these specifications and then add to the build processes. In this way no matter how badly other people mess up the format when it is pulled down from source control it will look acceptable.</p>
|
[
{
"answer_id": 286293,
"author": "Ben McNiel",
"author_id": 1455,
"author_profile": "https://Stackoverflow.com/users/1455",
"pm_score": 1,
"selected": false,
"text": "ServiceLocator.Logger.WriteDefault(string.format(\"{0}{1}\"\n ,foo\n ,bar)\n ,Logging.SuperDuper); \n if( foo\n && ( bar \n || baz \n || apples \n || oranges)\n && IsFoo()\n && IsBar() ){\n }\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1455/"
] |
286,123
|
<p>I have to read a txt file with lines formated like this:</p>
<pre>
1: (G, 2), (F, 3)
2: (G, 2), (F, 3)
3: (F, 4), (G, 5)
4: (F, 4), (G, 5)
5: (F, 6), (c, w)
6: (p, f), (G, 7)
7: (G, 7), (G, 7)
w: (c, w), (c, w)
</pre>
<p>Each line will feed a struct with its data (the 5 numbers or letters in it).<br>
What's the best way to read the line and get the strings I want?<br>
I'm currently using a long sequence of conditions using <code>fgetc</code> but that seems ugly and not very smart.<br>
I can't use arrays because the lines may vary in size if the numbers have two digits.</p>
|
[
{
"answer_id": 286138,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "fgets() #include <stdio.h>\n\nint main(void)\n{\n char line[256];\n while(fgets(line, sizeof(line), stdin) != NULL) // fgets returns NULL on EOF\n {\n // process line; line is guaranteed to be null-terminated, but it might not end in a\n // newline character '\\n' if the line was longer than the buffer size (in this case,\n // 256 characters)\n }\n\n return 0;\n}"
},
{
"answer_id": 286151,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "fscanf(file,\"%c: (%c, %c), (%c, %c)\", &first,&second,&third,&fourth,&fifth);\n"
},
{
"answer_id": 286172,
"author": "che",
"author_id": 7806,
"author_profile": "https://Stackoverflow.com/users/7806",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\n\nvoid main(int argc, char **argv) {\n FILE * f;\n f = fopen(argv[1], \"r\");\n\n while (1) {\n char char_or_num[32][5]; // five string arrays, up to 32 chars\n int i;\n int did_read;\n\n did_read = fscanf(f, \"%32[0-9a-zA-Z]: (%32[0-9a-zA-Z], %32[0-9a-zA-Z]), (%32[0-9a-zA-Z], %32[0-9a-zA-Z])\\n\", char_or_num[0], char_or_num[1], char_or_num[2], char_or_num[3], char_or_num[4]);\n if (did_read != 5) {\n break;\n }\n printf(\"%s, %s, %s, %s, %s\\n\", char_or_num[0], char_or_num[1], char_or_num[2], char_or_num[3], char_or_num[4]);\n }\n\n fclose(f);\n}\n"
},
{
"answer_id": 286318,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " fscanf(fp, \"%[^:]: (%[^,], %[^)]), (%[^,], %[^)])\", a, b, c, d, e);\n"
},
{
"answer_id": 286320,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": true,
"text": "#include <stdio.h>\n\nint main (void)\n{\n char buf[81]; /* Support lines up to 80 characters */\n char parts[5][11]; /* Support up to 10 characters in each part */\n\n while (fgets(buf, sizeof(buf), stdin) != NULL)\n {\n if (sscanf(buf, \"%10[^:]: (%10[^,], %10[^)]), (%10[^,], %10[^)])\",\n parts[0], parts[1], parts[2], parts[3], parts[4]) == 5)\n {\n printf(\"parts: %s, %s, %s, %s, %s\\n\",\n parts[0], parts[1], parts[2], parts[3], parts[4]);\n }\n else\n {\n printf(\"Invalid input: %s\", buf);\n }\n }\n return 0;\n}\n $ ./test\n1: (G, 2), (F, 3)\n2: (G, 2), (F, 3)\n3: (F, 4), (G, 5)\n4: (F, 4), (G, 5)\n5: (F, 6), (c, w)\n6: (p, f), (G, 7)\n7: (G, 7), (G, 7)\nw: (c, w), (c, w)\nparts: 1, G, 2, F, 3\nparts: 2, G, 2, F, 3\nparts: 3, F, 4, G, 5\nparts: 4, F, 4, G, 5\nparts: 5, F, 6, c, w\nparts: 6, p, f, G, 7\nparts: 7, G, 7, G, 7\nparts: w, c, w, c, w\n %c"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9835/"
] |
286,124
|
<p>How can I test <code>Controller.ViewData.ModelState</code>? I would prefer to do it without any mock framework. </p>
|
[
{
"answer_id": 589350,
"author": "Scott Hanselman",
"author_id": 6380,
"author_profile": "https://Stackoverflow.com/users/6380",
"pm_score": 7,
"selected": true,
"text": "// Test for required \"FirstName\".\n controller.ViewData.ModelState.Clear();\n\n newCustomer = new Customer\n {\n FirstName = \"\",\n LastName = \"Smith\",\n Zip = \"34275\", \n };\n\n controller.Create(newCustomer);\n\n // Make sure that our validation found the error!\n Assert.IsTrue(controller.ViewData.ModelState.Count == 1, \n \"FirstName must be required.\");\n"
},
{
"answer_id": 5580363,
"author": "VaSSaV",
"author_id": 696691,
"author_profile": "https://Stackoverflow.com/users/696691",
"pm_score": 5,
"selected": false,
"text": "//[Required]\n//public string Name { get; set; }\n//[Required]\n//public string Description { get; set; }\n\nProductModelEdit model = new ProductModelEdit() ;\n//Init ModelState\nvar modelBinder = new ModelBindingContext()\n{\n ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(\n () => model, model.GetType()),\n ValueProvider=new NameValueCollectionValueProvider(\n new NameValueCollection(), CultureInfo.InvariantCulture)\n};\nvar binder=new DefaultModelBinder().BindModel(\n new ControllerContext(),modelBinder );\nProductController.ModelState.Clear();\nProductController.ModelState.Merge(modelBinder.ModelState);\n\nViewResult result = (ViewResult)ProductController.CreateProduct(null,model);\nAssert.IsTrue(result.ViewData.ModelState[\"Name\"].Errors.Count > 0);\nAssert.True(result.ViewData.ModelState[\"Description\"].Errors.Count > 0);\nAssert.True(!result.ViewData.ModelState.IsValid);\n"
},
{
"answer_id": 38289159,
"author": "Bart Verkoeijen",
"author_id": 70182,
"author_profile": "https://Stackoverflow.com/users/70182",
"pm_score": 4,
"selected": false,
"text": "var controller = new MyController();\ncontroller.Configuration = new HttpConfiguration();\nvar model = new MyModel();\n\ncontroller.Validate(model);\nvar result = controller.MyMethod(model);\n"
},
{
"answer_id": 49393360,
"author": "Paul - Soura Tech LLC",
"author_id": 3071582,
"author_profile": "https://Stackoverflow.com/users/3071582",
"pm_score": 4,
"selected": false,
"text": "using Microsoft.AspNetCore.Mvc;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\n\nnamespace MyExtension\n{\n public static void BindViewModel<T>(this Controller controller, T model)\n {\n if (model == null) return;\n\n var context = new ValidationContext(model, null, null);\n var results = new List<ValidationResult>();\n\n if (!Validator.TryValidateObject(model, context, results, true))\n {\n controller.ModelState.Clear();\n foreach (ValidationResult result in results)\n {\n var key = result.MemberNames.FirstOrDefault() ?? \"\";\n controller.ModelState.AddModelError(key, result.ErrorMessage);\n }\n }\n }\n}\n public class MyViewModel\n{\n [Required]\n public string Name { get; set; }\n}\n public async void MyUnitTest()\n{\n // helper method to create instance of the Controller\n var controller = this.CreateController();\n\n var model = new MyViewModel\n {\n Name = null\n };\n\n // here we call the extension method to validate the model\n // and set the errors to the Controller's ModelState\n controller.BindViewModel(model);\n\n var result = await controller.ActionName(model);\n\n Assert.NotNull(result);\n var viewResult = Assert.IsType<BadRequestObjectResult>(result);\n}\n"
},
{
"answer_id": 52611541,
"author": "abovetempo",
"author_id": 7231971,
"author_profile": "https://Stackoverflow.com/users/7231971",
"pm_score": 2,
"selected": false,
"text": "//[Required]\n//public string Name { get; set; }\n//[Required]\n//public string Description { get; set; }\n ProductModelEdit model = new ProductModelEdit() ;\n//Init ModelState\nvar modelBinder = new ModelBindingContext()\n{\n ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(\n () => model, model.GetType()),\n ValueProvider=new NameValueCollectionValueProvider(\n new NameValueCollection(), CultureInfo.InvariantCulture)\n};\nvar binder=new DefaultModelBinder().BindModel(\n new ControllerContext(),modelBinder );\nProductController.ModelState.Clear();\nProductController.ModelState.Merge(modelBinder.ModelState);\n\nViewResult result = (ViewResult)ProductController.CreateProduct(null,model);\nAssert.IsTrue(!result.ViewData.ModelState.IsValid);\n//Make sure Name has correct errors\nAssert.IsTrue(result.ViewData.ModelState[\"Name\"].Errors.Count > 0);\nAssert.AreEqual(result.ViewData.ModelState[\"Name\"].Errors[0].ErrorMessage, \"Required\");\n//Make sure Description has correct errors\nAssert.IsTrue(result.ViewData.ModelState[\"Description\"].Errors.Count > 0);\nAssert.AreEqual(result.ViewData.ModelState[\"Description\"].Errors[0].ErrorMessage, \"Required\");\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32173/"
] |
286,132
|
<p>I have developed a simple mechanism for my mvc website to pull in html via jquery which then populates a specified div. All is well and it looks cool.<br>
My problem is that i'm now creating html markup inside of my controller (Which is very easy to do in VB.net btw) I'd rather not mix up the sepparation of concerns.</p>
<p>Is it possible to use a custom 'MVC View User Control' to suit this need? Can I create an instance of a control, pass in the model data and render to html? It would then be a simple matter of rendering and passing back to the calling browser.</p>
|
[
{
"answer_id": 286177,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "render :partial => 'yourfilename' RenderPartial"
},
{
"answer_id": 286381,
"author": "Christian Dalager",
"author_id": 11239,
"author_profile": "https://Stackoverflow.com/users/11239",
"pm_score": 3,
"selected": false,
"text": " public PartialViewResult LoginForm()\n {\n var model = // get model data from somewhere\n return PartialView(model);\n } $('#targetdiv').load('/MyController/LoginForm',function(){alert('complete!');});"
},
{
"answer_id": 294676,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 3,
"selected": true,
"text": "<% Html.RenderPartial(\"MyControl\") %>\n public ActionResult MyControl ()\n{\n // get modelData\n\n render View (modelData);\n}\n <% Html.RenderPartial(\"MyControl\", ViewData.Model) %>\n public class MyControlViewData\n{\n public string Name { get; set; }\n public string Email { get; set; }\n}\n\npublic partial class MyControl : System.Web.Mvc.ViewUserControl <MyControlViewData>\n{\n}\n <% Html.RenderPartial(\"MyControl\", new MyControlViewData ()\n {\n Name= ViewData.Model.FirstName,\n Email = ViewData.Model.Email,\n });\n %>\n"
},
{
"answer_id": 1052781,
"author": "pupeno",
"author_id": 6068,
"author_profile": "https://Stackoverflow.com/users/6068",
"pm_score": 5,
"selected": false,
"text": "/// <summary>\n/// Render a view into a string. It's a hack, it may fail badly.\n/// </summary>\n/// <param name=\"name\">Name of the view, that is, its path.</param>\n/// <param name=\"data\">Data to pass to the view, a model or something like that.</param>\n/// <returns>A string with the (HTML of) view.</returns>\npublic static string RenderPartialToString(string controlName, object viewData) {\n ViewPage viewPage = new ViewPage() { ViewContext = new ViewContext() };\n viewPage.Url = GetBogusUrlHelper();\n\n viewPage.ViewData = new ViewDataDictionary(viewData);\n viewPage.Controls.Add(viewPage.LoadControl(controlName));\n\n StringBuilder sb = new StringBuilder();\n using (StringWriter sw = new StringWriter(sb)) {\n using (HtmlTextWriter tw = new HtmlTextWriter(sw)) {\n viewPage.RenderControl(tw);\n }\n }\n\n return sb.ToString();\n}\n\npublic static UrlHelper GetBogusUrlHelper() {\n var httpContext = HttpContext.Current;\n\n if (httpContext == null) {\n var request = new HttpRequest(\"/\", Config.Url.ToString(), \"\");\n var response = new HttpResponse(new StringWriter());\n httpContext = new HttpContext(request, response);\n }\n\n var httpContextBase = new HttpContextWrapper(httpContext);\n var routeData = new RouteData();\n var requestContext = new RequestContext(httpContextBase, routeData);\n\n return new UrlHelper(requestContext);\n}\n string view = RenderPartialToString(\"~/Views/Controller/AView.ascx\", someModelObject); \n"
},
{
"answer_id": 3296424,
"author": "Rob King",
"author_id": 393307,
"author_profile": "https://Stackoverflow.com/users/393307",
"pm_score": 2,
"selected": false,
"text": "<% Html.RenderAction(\"Action\", \"Controller\"); %>\n <div class=\"onload\">/controller/action</div>\n <script type=\"text/javascript\">\n $.ajaxSetup({ cache: false });\n\n $(document).ready(function () {\n $('div.onload').each(function () {\n var source = $(this).html();\n if (source != \"\") {\n $(this).load(source);\n }\n });\n });\n</script>\n"
},
{
"answer_id": 14284339,
"author": "Paco Lf",
"author_id": 1476071,
"author_profile": "https://Stackoverflow.com/users/1476071",
"pm_score": 0,
"selected": false,
"text": "public PartialViewResult yourpartialviewresult()\n{\n var yourModel\n return PartialView(\"yourPartialView\", yourModel);\n}\n $.ajax({\n type: 'GET',\n url: '/home/yourpartialviewresult',\n dataType: 'html', //be sure to use html dataType\n contentType: 'application/json; charset=utf-8',\n success: function(data){\n $(container).html(data);\n },\n complete: function(){ }\n }); \n"
},
{
"answer_id": 45574937,
"author": "Himanshu Patel",
"author_id": 1376658,
"author_profile": "https://Stackoverflow.com/users/1376658",
"pm_score": 0,
"selected": false,
"text": "System.Web.Mvc.Html.PartialExtensions.Partial(html, \"~/Views/Orders/OrdersPartialView.cshtml\", orderModel).ToString();\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30576/"
] |
286,141
|
<p>How do I remove all attributes which are <code>undefined</code> or <code>null</code> in a JavaScript object?</p>
<p>(Question is similar to <a href="https://stackoverflow.com/questions/208105/how-to-remove-a-property-from-a-javascript-object">this one</a> for Arrays)</p>
|
[
{
"answer_id": 286145,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 4,
"selected": false,
"text": "delete var obj = { };\nobj.theProperty = 1;\ndelete obj.theProperty;\n"
},
{
"answer_id": 286162,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 9,
"selected": true,
"text": "var test = {\n test1: null,\n test2: 'somestring',\n test3: 3,\n}\n\nfunction clean(obj) {\n for (var propName in obj) {\n if (obj[propName] === null || obj[propName] === undefined) {\n delete obj[propName];\n }\n }\n return obj\n}\n\nconsole.log(test);\nconsole.log(clean(test)); function clean(obj) {\n var propNames = Object.getOwnPropertyNames(obj);\n for (var i = 0; i < propNames.length; i++) {\n var propName = propNames[i];\n if (obj[propName] === null || obj[propName] === undefined) {\n delete obj[propName];\n }\n }\n}\n test.test1 === null; // true\ntest.test1 == null; // true\n\ntest.notaprop === null; // false\ntest.notaprop == null; // true\n\ntest.notaprop === undefined; // true\ntest.notaprop == undefined; // true\n"
},
{
"answer_id": 12777816,
"author": "nguyên",
"author_id": 572180,
"author_profile": "https://Stackoverflow.com/users/572180",
"pm_score": 3,
"selected": false,
"text": "! var r = {a: null, b: undefined, c:1};\nfor(var k in r)\n if(!r[k]) delete r[k];\n"
},
{
"answer_id": 24190282,
"author": "Wumms",
"author_id": 1097958,
"author_profile": "https://Stackoverflow.com/users/1097958",
"pm_score": 5,
"selected": false,
"text": "/**\n * Delete all null (or undefined) properties from an object.\n * Set 'recurse' to true if you also want to delete properties in nested objects.\n */\nfunction delete_null_properties(test, recurse) {\n for (var i in test) {\n if (test[i] === null) {\n delete test[i];\n } else if (recurse && typeof test[i] === 'object') {\n delete_null_properties(test[i], recurse);\n }\n }\n}\n"
},
{
"answer_id": 30386744,
"author": "Alexandre Farber",
"author_id": 4927045,
"author_profile": "https://Stackoverflow.com/users/4927045",
"pm_score": 5,
"selected": false,
"text": "removeUndefined = function(json){\n return JSON.parse(JSON.stringify(json))\n}\n"
},
{
"answer_id": 34949831,
"author": "sam",
"author_id": 1660475,
"author_profile": "https://Stackoverflow.com/users/1660475",
"pm_score": 3,
"selected": false,
"text": "function removeEmptyValues(obj) {\n for (var propName in obj) {\n if (!obj[propName] || obj[propName].length === 0) {\n delete obj[propName];\n } else if (typeof obj[propName] === 'object') {\n removeEmptyValues(obj[propName]);\n }\n }\n return obj;\n }\n"
},
{
"answer_id": 35871405,
"author": "Ben",
"author_id": 3150636,
"author_profile": "https://Stackoverflow.com/users/3150636",
"pm_score": 7,
"selected": false,
"text": "var obj = {name: 'John', age: null};\n\nvar compacted = _.pickBy(obj);\n _.pick(obj, _.identity)"
},
{
"answer_id": 36579096,
"author": "Alex Johnson",
"author_id": 1508105,
"author_profile": "https://Stackoverflow.com/users/1508105",
"pm_score": 2,
"selected": false,
"text": "_.pickBy _.pick var obj = {name: 'John', age: null};\n\nvar compacted = _.pick(obj, function(value) {\n return value !== null && value !== undefined;\n});\n"
},
{
"answer_id": 36955172,
"author": "Łukasz Jagodziński",
"author_id": 1584746,
"author_profile": "https://Stackoverflow.com/users/1584746",
"pm_score": 2,
"selected": false,
"text": "undefined lodash null undefined function omitUndefinedDeep(obj) {\n return _.reduce(obj, function(result, value, key) {\n if (_.isObject(value)) {\n result[key] = omitUndefinedDeep(value);\n }\n else if (!_.isUndefined(value)) {\n result[key] = value;\n }\n return result;\n }, {});\n}\n"
},
{
"answer_id": 38340730,
"author": "Rotareti",
"author_id": 1612318,
"author_profile": "https://Stackoverflow.com/users/1612318",
"pm_score": 10,
"selected": false,
"text": "let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));\n function removeEmpty(obj) {\n return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));\n}\n function removeEmpty(obj) {\n return Object.fromEntries(\n Object.entries(obj)\n .filter(([_, v]) => v != null)\n .map(([k, v]) => [k, v === Object(v) ? removeEmpty(v) : v])\n );\n}\n Object.keys(obj).forEach((k) => obj[k] == null && delete obj[k]);\n let o = Object.keys(obj)\n .filter((k) => obj[k] != null)\n .reduce((a, k) => ({ ...a, [k]: obj[k] }), {});\n function removeEmpty(obj) {\n return Object.entries(obj)\n .filter(([_, v]) => v != null)\n .reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});\n}\n function removeEmpty(obj) {\n return Object.entries(obj)\n .filter(([_, v]) => v != null)\n .reduce(\n (acc, [k, v]) => ({ ...acc, [k]: v === Object(v) ? removeEmpty(v) : v }),\n {}\n );\n}\n function removeEmpty(obj) {\n const newObj = {};\n Object.entries(obj).forEach(([k, v]) => {\n if (v === Object(v)) {\n newObj[k] = removeEmpty(v);\n } else if (v != null) {\n newObj[k] = obj[k];\n }\n });\n return newObj;\n}\n function removeEmpty(obj) {\n return Object.keys(obj)\n .filter(function (k) {\n return obj[k] != null;\n })\n .reduce(function (acc, k) {\n acc[k] = obj[k];\n return acc;\n }, {});\n}\n function removeEmpty(obj) {\n const newObj = {};\n Object.keys(obj).forEach(function (k) {\n if (obj[k] && typeof obj[k] === \"object\") {\n newObj[k] = removeEmpty(obj[k]);\n } else if (obj[k] != null) {\n newObj[k] = obj[k];\n }\n });\n return newObj;\n}\n function removeEmpty(obj) {\n return Object.keys(obj)\n .filter(function (k) {\n return obj[k] != null;\n })\n .reduce(function (acc, k) {\n acc[k] = typeof obj[k] === \"object\" ? removeEmpty(obj[k]) : obj[k];\n return acc;\n }, {});\n}\n"
},
{
"answer_id": 40517249,
"author": "Alex Mueller",
"author_id": 1489958,
"author_profile": "https://Stackoverflow.com/users/1489958",
"pm_score": 4,
"selected": false,
"text": "JSON.stringify JSON.parse var exampleObject = {\n string: 'value',\n emptyString: '',\n integer: 0,\n nullValue: null,\n array: [1, 2, 3],\n object: {\n string: 'value',\n emptyString: '',\n integer: 0,\n nullValue: null,\n array: [1, 2, 3]\n },\n arrayOfObjects: [\n {\n string: 'value',\n emptyString: '',\n integer: 0,\n nullValue: null,\n array: [1, 2, 3]\n },\n {\n string: 'value',\n emptyString: '',\n integer: 0,\n nullValue: null,\n array: [1, 2, 3]\n }\n ]\n};\n function replaceUndefinedOrNull(key, value) {\n if (value === null || value === undefined) {\n return undefined;\n }\n\n return value;\n}\n exampleObject = JSON.stringify(exampleObject, replaceUndefinedOrNull);\nexampleObject = JSON.parse(exampleObject);\n"
},
{
"answer_id": 40844595,
"author": "Amio.io",
"author_id": 1075289,
"author_profile": "https://Stackoverflow.com/users/1075289",
"pm_score": 3,
"selected": false,
"text": "null undefined false const obj = {a:1, b: undefined, c: null, d: 1}\nR.pickBy(R.identity, obj)\n false isNil() const obj = {a:1, b: undefined, c: null, d: 1, e: false}\nR.pickBy(v => !R.isNil(v), obj)\n"
},
{
"answer_id": 42658601,
"author": "Dana Woodman",
"author_id": 529829,
"author_profile": "https://Stackoverflow.com/users/529829",
"pm_score": 2,
"selected": false,
"text": "_.omitBy({a: 1, b: null}, (v) => !v)\n"
},
{
"answer_id": 42755601,
"author": "bsyk",
"author_id": 2242975,
"author_profile": "https://Stackoverflow.com/users/2242975",
"pm_score": 2,
"selected": false,
"text": "// Helper to remove undefined or null properties from an object\nfunction removeEmpty(obj) {\n // Protect against null/undefined object passed in\n return Object.keys(obj || {}).reduce((x, k) => {\n // Check for null or undefined\n if (obj[k] != null) {\n x[k] = obj[k];\n }\n return x;\n }, {});\n}\n"
},
{
"answer_id": 42848007,
"author": "Jin Zhao",
"author_id": 2718861,
"author_profile": "https://Stackoverflow.com/users/2718861",
"pm_score": 3,
"selected": false,
"text": "const removeEmpty = (obj) => {\n return Object.keys(obj).filter(key => obj[key]).reduce(\n (newObj, key) => {\n newObj[key] = obj[key]\n return newObj\n }, {}\n )\n}\n"
},
{
"answer_id": 43629975,
"author": "Michael J. Zoidl",
"author_id": 1624739,
"author_profile": "https://Stackoverflow.com/users/1624739",
"pm_score": 3,
"selected": false,
"text": ".length > 0 const MY_OBJECT = { f: 'te', a: [] }\n\nObject.keys(MY_OBJECT)\n .filter(f => !!MY_OBJECT[f] && MY_OBJECT[f].length > 0)\n .reduce((r, i) => { r[i] = MY_OBJECT[i]; return r; }, {});\n"
},
{
"answer_id": 44032137,
"author": "JeffD23",
"author_id": 3808414,
"author_profile": "https://Stackoverflow.com/users/3808414",
"pm_score": 4,
"selected": false,
"text": "null undefined _.omitBy(obj, _.isNil)"
},
{
"answer_id": 44939678,
"author": "dpmott",
"author_id": 2773846,
"author_profile": "https://Stackoverflow.com/users/2773846",
"pm_score": 2,
"selected": false,
"text": "const queryParams = { a: 'a', b: 'b', c: 'c', d: undefined, e: null, f: '', g: 0 };\nconst cleanParams = Object.keys(queryParams) \n .filter(key => queryParams[key] != null)\n .reduce((acc, key) => Object.assign(acc, { [key]: queryParams[key] }), {});\n// { a: 'a', b: 'b', c: 'c', f: '', g: 0 }\n"
},
{
"answer_id": 46451724,
"author": "DaniOcean",
"author_id": 1353721,
"author_profile": "https://Stackoverflow.com/users/1353721",
"pm_score": 2,
"selected": false,
"text": "const clean = e => e instanceof Object ? Object.entries(e).reduce((o, [k, v]) => {\n if (typeof v === 'boolean' || v) o[k] = clean(v);\n return o;\n}, e instanceof Array ? [] : {}) : e;\n function filterEmpty(obj, [key, val]) {\n if (typeof val === 'boolean' || val) {\n obj[key] = clean(val)\n };\n\n return obj;\n}\n\nfunction clean(entry) {\n if (entry instanceof Object) {\n const type = entry instanceof Array ? [] : {};\n const entries = Object.entries(entry);\n\n return entries.reduce(filterEmpty, type);\n }\n\n return entry;\n}\n"
},
{
"answer_id": 47205128,
"author": "bharath muppa",
"author_id": 4029794,
"author_profile": "https://Stackoverflow.com/users/4029794",
"pm_score": 3,
"selected": false,
"text": "removeEmptyKeysFromObject(obj) {\n Object.keys(obj).forEach(key => {\n if (Object.prototype.toString.call(obj[key]) === '[object Date]' && (obj[key].toString().length === 0 || obj[key].toString() === 'Invalid Date')) {\n delete obj[key];\n } else if (obj[key] && typeof obj[key] === 'object') {\n this.removeEmptyKeysFromObject(obj[key]);\n } else if (obj[key] == null || obj[key] === '') {\n delete obj[key];\n }\n\n if (obj[key]\n && typeof obj[key] === 'object'\n && Object.keys(obj[key]).length === 0\n && Object.prototype.toString.call(obj[key]) !== '[object Date]') {\n delete obj[key];\n }\n});\n return obj;\n}"
},
{
"answer_id": 51600150,
"author": "Felippe Nardi",
"author_id": 1762125,
"author_profile": "https://Stackoverflow.com/users/1762125",
"pm_score": 2,
"selected": false,
"text": "nulls reduce const stripNulls = (obj) => {\n return Object.keys(obj).reduce((acc, current) => {\n if (obj[current] !== null) {\n return { ...acc, [current]: obj[current] }\n }\n return acc\n }, {})\n}\n"
},
{
"answer_id": 51686226,
"author": "Ben Carp",
"author_id": 7224430,
"author_profile": "https://Stackoverflow.com/users/7224430",
"pm_score": 1,
"selected": false,
"text": "// General cleanObj function\nconst cleanObj = (valsToRemoveArr, obj) => {\n Object.keys(obj).forEach( (key) =>\n if (valsToRemoveArr.includes(obj[key])){\n delete obj[key]\n }\n })\n}\n\ncleanObj([undefined, null], obj)\n const getObjWithoutVals = (dontReturnValsArr, obj) => {\n const cleanObj = {}\n Object.entries(obj).forEach( ([key, val]) => {\n if(!dontReturnValsArr.includes(val)){\n cleanObj[key]= val\n } \n })\n return cleanObj\n}\n\n//To get a new object without `null` or `undefined` run: \nconst nonEmptyObj = getObjWithoutVals([undefined, null], obj)\n"
},
{
"answer_id": 52518442,
"author": "Yinon",
"author_id": 3027703,
"author_profile": "https://Stackoverflow.com/users/3027703",
"pm_score": 2,
"selected": false,
"text": "const cleanObj = Object.entries(objToClean).reduce((acc, [key, value]) => {\n if (value) {\n acc[key] = value;\n }\n return acc;\n }, {});\n"
},
{
"answer_id": 52831153,
"author": "Hardik Pithva",
"author_id": 4790490,
"author_profile": "https://Stackoverflow.com/users/4790490",
"pm_score": 2,
"selected": false,
"text": "... forEach let obj = { a: 1, b: \"b\", c: undefined, d: null };\nlet cleanObj = {};\n\nObject.keys(obj).forEach(val => {\n const newVal = obj[val];\n cleanObj = newVal ? { ...cleanObj, [val]: newVal } : cleanObj;\n});\n\nconsole.info(cleanObj);"
},
{
"answer_id": 53824356,
"author": "Peter Aron Zentai",
"author_id": 1269946,
"author_profile": "https://Stackoverflow.com/users/1269946",
"pm_score": 0,
"selected": false,
"text": "const stripUndef = obj => \n Object.keys(obj)\n .reduce((p, c) => ({ ...p, ...(x[c] === undefined ? { } : { [c]: x[c] })}), {});\n"
},
{
"answer_id": 54455779,
"author": "lewtur",
"author_id": 7012762,
"author_profile": "https://Stackoverflow.com/users/7012762",
"pm_score": 0,
"selected": false,
"text": "const keys = Object.keys(objectWithNulls).filter(key => objectWithNulls[key]);\nconst pairs = keys.map(key => ({ [key]: objectWithNulls[key] }));\n\nconst objectWithoutNulls = pairs.reduce((val, acc) => ({ ...val, ...acc }));\n filter(key => objectWithNulls[key]) 0 false undefined null filter(key => objectWithNulls[key] !== undefined)"
},
{
"answer_id": 54707141,
"author": "Scotty Jamison",
"author_id": 7696223,
"author_profile": "https://Stackoverflow.com/users/7696223",
"pm_score": 4,
"selected": false,
"text": "const removeEmptyValues = obj => (\n JSON.parse(JSON.stringify(obj, (k,v) => v ?? undefined))\n)\n removeEmptyValues({a:{x:1,y:null,z:undefined}}) // Returns {a:{x:1}}\n (k,v) => v!=null ? v : undefined"
},
{
"answer_id": 56093495,
"author": "L. Zampetti",
"author_id": 5872513,
"author_profile": "https://Stackoverflow.com/users/5872513",
"pm_score": 2,
"selected": false,
"text": "export function skipEmpties(dirty) {\n let item;\n if (Array.isArray(dirty)) {\n item = dirty.map(x => skipEmpties(x)).filter(value => value !== undefined);\n return item.length ? item : undefined;\n } else if (dirty && typeof dirty === 'object') {\n item = {};\n Object.keys(dirty).forEach(key => {\n const value = skipEmpties(dirty[key]);\n if (value !== undefined) {\n item[key] = value;\n }\n });\n return Object.keys(item).length ? item : undefined;\n } else {\n return dirty === null ? undefined : dirty;\n }\n}\n"
},
{
"answer_id": 56325271,
"author": "peralmq",
"author_id": 350195,
"author_profile": "https://Stackoverflow.com/users/350195",
"pm_score": 3,
"selected": false,
"text": ".filter Object.keys(obj).reduce((acc, key) => (obj[key] === undefined ? acc : {...acc, [key]: obj[key]}), {})\n"
},
{
"answer_id": 57195634,
"author": "Vardaman PK",
"author_id": 11521196,
"author_profile": "https://Stackoverflow.com/users/11521196",
"pm_score": 1,
"selected": false,
"text": "jsObject = JSON.parse(JSON.stringify(jsObject), (key, value) => {\n if (value == null || value == '' || value == [] || value == {})\n return undefined;\n return value;\n });\n"
},
{
"answer_id": 57625661,
"author": "chickens",
"author_id": 1602301,
"author_profile": "https://Stackoverflow.com/users/1602301",
"pm_score": 8,
"selected": false,
"text": "\"\" 0 false null undefined Object.entries(obj).reduce((a,[k,v]) => (v ? (a[k]=v, a) : a), {})\n null undefined Object.entries(obj).reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {})\n null Object.entries(obj).reduce((a,[k,v]) => (v === null ? a : (a[k]=v, a)), {})\n undefined Object.entries(obj).reduce((a,[k,v]) => (v === undefined ? a : (a[k]=v, a)), {})\n null undefined const cleanEmpty = obj => Object.entries(obj)\n .map(([k,v])=>[k,v && typeof v === \"object\" ? cleanEmpty(v) : v])\n .reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {});\n const cleanEmpty = obj => {\n if (Array.isArray(obj)) { \n return obj\n .map(v => (v && typeof v === 'object') ? cleanEmpty(v) : v)\n .filter(v => !(v == null)); \n } else { \n return Object.entries(obj)\n .map(([k, v]) => [k, v && typeof v === 'object' ? cleanEmpty(v) : v])\n .reduce((a, [k, v]) => (v == null ? a : (a[k]=v, a)), {});\n } \n}\n"
},
{
"answer_id": 60485904,
"author": "JHH",
"author_id": 1226020,
"author_profile": "https://Stackoverflow.com/users/1226020",
"pm_score": -1,
"selected": false,
"text": "Object.assign() false Object.assign({}, ...Object.entries(obj).map(([k,v]) => v != null && {[k]: v]))\n"
},
{
"answer_id": 60887364,
"author": "Benny Neugebauer",
"author_id": 451634,
"author_profile": "https://Stackoverflow.com/users/451634",
"pm_score": 0,
"selected": false,
"text": "const someObject = {\n a: null,\n b: 'someString',\n c: 3,\n d: undefined\n};\n\nfor (let [key, value] of Object.entries(someObject)) {\n if (value === null || value === undefined) delete someObject[key];\n}\n\nconsole.log('Sanitized', someObject);"
},
{
"answer_id": 61764079,
"author": "Arturo Montoya",
"author_id": 6526093,
"author_profile": "https://Stackoverflow.com/users/6526093",
"pm_score": 0,
"selected": false,
"text": "ES6 arrow function and ternary operator:\nObject.entries(obj).reduce((acc, entry) => {\n const [key, value] = entry\n if (value !== undefined) acc[key] = value;\n return acc;\n}, {})\n\n\n const obj = {test:undefined, test1:1 ,test12:0, test123:false};\n const newObj = Object.entries(obj).reduce((acc, entry) => {\n const [key, value] = entry\n if (value !== undefined) acc[key] = value;\n return acc;\n }, {})\n console.log(newObj)\n\n\n\n const obj = {test:undefined, test1:1 ,test12:0, test123:false};\n const newObj = Object.entries(obj).reduce((acc, entry) => {\n const [key, value] = entry\n if (value !== undefined) acc[key] = value;\n return acc;\n }, {})\n console.log(newObj)"
},
{
"answer_id": 61768333,
"author": "Emmanuel N K",
"author_id": 2969074,
"author_profile": "https://Stackoverflow.com/users/2969074",
"pm_score": 2,
"selected": false,
"text": "defaults=[undefined, null, '', NaN] const cleanEmpty = function(obj, defaults = [undefined, null, NaN, '']) {\n if (!defaults.length) return obj\n if (defaults.includes(obj)) return\n\n if (Array.isArray(obj))\n return obj\n .map(v => v && typeof v === 'object' ? cleanEmpty(v, defaults) : v)\n .filter(v => !defaults.includes(v))\n\n return Object.entries(obj).length \n ? Object.entries(obj)\n .map(([k, v]) => ([k, v && typeof v === 'object' ? cleanEmpty(v, defaults) : v]))\n .reduce((a, [k, v]) => (defaults.includes(v) ? a : { ...a, [k]: v}), {}) \n : obj\n}\n // based off the recursive cleanEmpty function by @chickens. \n// This one can also handle Date objects correctly \n// and has a defaults list for values you want stripped.\n\nconst cleanEmpty = function(obj, defaults = [undefined, null, NaN, '']) {\n if (!defaults.length) return obj\n if (defaults.includes(obj)) return\n\n if (Array.isArray(obj))\n return obj\n .map(v => v && typeof v === 'object' ? cleanEmpty(v, defaults) : v)\n .filter(v => !defaults.includes(v))\n\n return Object.entries(obj).length \n ? Object.entries(obj)\n .map(([k, v]) => ([k, v && typeof v === 'object' ? cleanEmpty(v, defaults) : v]))\n .reduce((a, [k, v]) => (defaults.includes(v) ? a : { ...a, [k]: v}), {}) \n : obj\n}\n\n\n// testing\n\nconsole.log('testing: undefined \\n', cleanEmpty(undefined))\nconsole.log('testing: null \\n',cleanEmpty(null))\nconsole.log('testing: NaN \\n',cleanEmpty(NaN))\nconsole.log('testing: empty string \\n',cleanEmpty(''))\nconsole.log('testing: empty array \\n',cleanEmpty([]))\nconsole.log('testing: date object \\n',cleanEmpty(new Date(1589339052 * 1000)))\nconsole.log('testing: nested empty arr \\n',cleanEmpty({ 1: { 2 :null, 3: [] }}))\nconsole.log('testing: comprehensive obj \\n', cleanEmpty({\n a: 5,\n b: 0,\n c: undefined,\n d: {\n e: null,\n f: [{\n a: undefined,\n b: new Date(),\n c: ''\n }]\n },\n g: NaN,\n h: null\n}))\nconsole.log('testing: different defaults \\n', cleanEmpty({\n a: 5,\n b: 0,\n c: undefined,\n d: {\n e: null,\n f: [{\n a: undefined,\n b: '',\n c: new Date()\n }]\n },\n g: [0, 1, 2, 3, 4],\n h: '',\n}, [undefined, null]))"
},
{
"answer_id": 62406569,
"author": "Agus Suhardi",
"author_id": 6251396,
"author_profile": "https://Stackoverflow.com/users/6251396",
"pm_score": 0,
"selected": false,
"text": "for (const objectKey of Object.keys(data)) {\n if (data[objectKey] === null || data[objectKey] === '' || data[objectKey] === 'null' || data[objectKey] === undefined) {\n delete data[objectKey];\n }\n }\n"
},
{
"answer_id": 62770539,
"author": "Shikyo",
"author_id": 1557162,
"author_profile": "https://Stackoverflow.com/users/1557162",
"pm_score": 1,
"selected": false,
"text": "function filterObject(obj, filter) {\n return Object.entries(obj)\n .map(([key, value]) => {\n return [key, value && typeof value === 'object'\n ? filterObject(value, filter)\n : value];\n })\n .reduce((acc, [key, value]) => {\n if (!filter.includes(value)) {\n acc[key] = value;\n }\n\n return acc;\n }, {});\n}\n const filtered = filterObject(originalObject, [null, '']);\n null ''"
},
{
"answer_id": 64447384,
"author": "ThomasReggi",
"author_id": 340688,
"author_profile": "https://Stackoverflow.com/users/340688",
"pm_score": 2,
"selected": false,
"text": "function objectDefined <T>(obj: T): T {\n const acc: Partial<T> = {};\n for (const key in obj) {\n if (obj[key] !== undefined) acc[key] = obj[key];\n }\n return acc as T;\n}\n function objectDefined(obj) {\n const acc = {};\n for (const key in obj) {\n if (obj[key] !== undefined) acc[key] = obj[key];\n }\n return acc;\n}\n"
},
{
"answer_id": 65263323,
"author": "aalaap",
"author_id": 44257,
"author_profile": "https://Stackoverflow.com/users/44257",
"pm_score": 2,
"selected": false,
"text": "const prune = obj => _.filterDeep(obj, (v) => !(_.isUndefined(v) || _.isNull(v)));\n prune(anObjectWithNulls) undefined null"
},
{
"answer_id": 66092400,
"author": "Zahirul Haque",
"author_id": 3863697,
"author_profile": "https://Stackoverflow.com/users/3863697",
"pm_score": 3,
"selected": false,
"text": "let obj = {\n\"id\": 1,\n\"firstName\": null,\n\"lastName\": null,\n\"address\": undefined,\n\"role\": \"customer\",\n\"photo\": \"fb79fd5d-06c9-4097-8fdc-6cebf73fab26/fc8efe82-2af4-4c81-bde7-8d2f9dd7994a.jpg\",\n\"location\": null,\n\"idNumber\": null,\n};\n\n let result = Object.entries(obj).reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {});\nconsole.log(result)"
},
{
"answer_id": 68863356,
"author": "Harsh Soni",
"author_id": 14058987,
"author_profile": "https://Stackoverflow.com/users/14058987",
"pm_score": 0,
"selected": false,
"text": "function filterObject(obj) {\n for (var propName in obj) {\n if (!(obj[propName] || obj[propName] === false)) {\n delete obj[propName];\n }\n }\n\n return obj;\n}\n"
},
{
"answer_id": 69497853,
"author": "Lysandro Carioca",
"author_id": 5914415,
"author_profile": "https://Stackoverflow.com/users/5914415",
"pm_score": 1,
"selected": false,
"text": "const filterNullishPropertiesFromObject = (obj) => {\n const newEntries = Object.entries(obj).filter(([_, value]) => {\n const nullish = value ?? null;\n return nullish !== null;\n });\n\n return Object.fromEntries(newEntries);\n};\n"
},
{
"answer_id": 69726359,
"author": "Guilherme Nimer",
"author_id": 11237109,
"author_profile": "https://Stackoverflow.com/users/11237109",
"pm_score": -1,
"selected": false,
"text": "const removeEmpty = obj => {\n if (Array.isArray(obj)) {\n return obj.map(v => (v && !(v instanceof Date) && typeof v === 'object' ? removeEmpty(v) : v)).filter(v => v)\n } else {\n return Object.entries(obj)\n .map(([k, v]) => [k, v && !(v instanceof Date) && typeof v === 'object' ? removeEmpty(v) : v])\n .reduce((a, [k, v]) => (typeof v !== 'boolean' && !v ? a : ((a[k] = v), a)), {})\n }\n }\n"
},
{
"answer_id": 70580481,
"author": "Koen Peters",
"author_id": 1236396,
"author_profile": "https://Stackoverflow.com/users/1236396",
"pm_score": 0,
"selected": false,
"text": "const removeEmptyKeys = (obj) => {\n Object.entries(obj).forEach(([k, v]) => {\n (v ?? delete obj[k])\n if (v && typeof v === 'object') {\n removeEmptyKeys(v)\n }\n })\n}\n"
},
{
"answer_id": 70630093,
"author": "Baptiste Arnaud",
"author_id": 5654715,
"author_profile": "https://Stackoverflow.com/users/5654715",
"pm_score": 0,
"selected": false,
"text": "reduce const removeUndefinedFields = <T>(obj: T): T =>\n Object.keys(obj).reduce(\n (acc, key) =>\n obj[key as keyof T] === undefined\n ? { ...acc }\n : { ...acc, [key]: obj[key as keyof T] },\n {} as T\n )\n"
},
{
"answer_id": 70771061,
"author": "U. Bulle",
"author_id": 5433463,
"author_profile": "https://Stackoverflow.com/users/5433463",
"pm_score": 0,
"selected": false,
"text": "function removeUndefinedProperties(obj) {\n return Object.keys(obj || {})\n .reduce((acc, key) => {\n const value = obj[key];\n switch (typeof value) {\n case 'object': {\n const cleanValue = removeUndefinedProperties(value); // recurse\n if (!Object.keys(cleanValue).length) {\n return { ...acc };\n }\n return { ...acc, [key]: cleanValue };\n }\n case 'undefined':\n return { ...acc };\n default:\n return { ...acc, [key]: value };\n }\n }, {});\n}\n unknown function removeUndefinedProperties(obj: unknown): unknown {\n return Object.keys(obj ?? {})\n .reduce((acc, key) => {\n const value = obj[key];\n switch (typeof value) {\n case 'object': {\n const cleanValue = removeUndefinedProperties(value); // recurse\n if (!Object.keys(cleanValue).length) {\n return { ...acc };\n }\n return { ...acc, [key]: cleanValue };\n }\n case 'undefined':\n return { ...acc };\n default:\n return { ...acc, [key]: value };\n }\n }, {});\n}\n"
},
{
"answer_id": 71184412,
"author": "prakhar tomar",
"author_id": 13860071,
"author_profile": "https://Stackoverflow.com/users/13860071",
"pm_score": 0,
"selected": false,
"text": "function objCleanUp(obj:any) {\n for (var attrKey in obj) {\n var attrValue = obj[attrKey];\n if (attrValue === null || attrValue === undefined || attrValue === \"\" || attrValue !== attrValue) {\n delete obj[attrKey];\n } else if (Object.prototype.toString.call(attrValue) === \"[object Object]\") {\n objCleanUp(attrValue);\n if(Object.keys(attrValue).length===0)delete obj[attrKey];\n } else if (Array.isArray(attrValue)) {\n attrValue.forEach(function (v,index) {\n objCleanUp(v);\n if(Object.keys(v).length===0)attrValue.splice(index,1);\n });\n if(attrValue.length===0)delete obj[attrKey];\n }\n }\n}\n\nobjCleanUp(myObject)\n"
},
{
"answer_id": 71815600,
"author": "ahmelq",
"author_id": 2722247,
"author_profile": "https://Stackoverflow.com/users/2722247",
"pm_score": 0,
"selected": false,
"text": "let obj = { a: 0, b: \"string\", c: undefined, d: null };\n\nObject.keys(obj).map(k => obj[k] == undefined ? delete obj[k] : obj[k] );\n obj { a: 0, b: \"string\" }"
},
{
"answer_id": 71816805,
"author": "Mohammed Rashad",
"author_id": 8133129,
"author_profile": "https://Stackoverflow.com/users/8133129",
"pm_score": 0,
"selected": false,
"text": "var testObject = {\n test1: \"null\",\n test2: null,\n test3: 'somestring',\n test4: 3,\n test5: \"undefined\",\n test6: undefined,\n}\n\nfunction removeObjectItem(obj){\n for (var key in obj) {\n if (String(obj[key]) === \"null\" || String(obj[key]) === \"undefined\") {\n delete obj[key];\n }\n }\n return obj\n}\nconsole.log(removeObjectItem(testObject))"
},
{
"answer_id": 71968391,
"author": "ABHIJEET KHIRE",
"author_id": 8621764,
"author_profile": "https://Stackoverflow.com/users/8621764",
"pm_score": 2,
"selected": false,
"text": "// basic object you have to clean \n// ️ input _object\nconst _object = {\n a: null,\n b: undefined,\n email: 'email@test.com',\n mob:88888888888,\n add:\"\"\n };\n \n// kays you have to remove having values included in array \n const CLEANER_VALUES = [null, undefined, '']\n \n// function to clean object pass the raw object and value format you have to clean\n const objectCleaner = (_object, _CLEANER_VALUES = CLEANER_VALUES) =>{\n const cleanedObj = {..._object};\n Object.keys(cleanedObj).forEach(key => {\n if (_CLEANER_VALUES.includes(cleanedObj[key])) {\n delete cleanedObj[key];\n }});\n \n return cleanedObj;\n \n }\n \n // calling function \n const __cleandedObject = objectCleaner(_object, CLEANER_VALUES);\n console.log('yup you have cleaned object', __cleandedObject); \n // ️ output { email: \"email@test.com\",mob: 88888888888 }\n\n "
},
{
"answer_id": 73068210,
"author": "Nivethan",
"author_id": 12719767,
"author_profile": "https://Stackoverflow.com/users/12719767",
"pm_score": 0,
"selected": false,
"text": "function cleanProps(object:Record<string, string>):Record<string, string> {\n let cleanObj = {};\n\n Object.keys(object).forEach((key) => {\n const property = object[key];\n cleanObj = property ? { ...cleanObj, [key]: property } : cleanObj;\n });\n\n return cleanObj;\n}\n\nexport default cleanProps;\n\n interface Filters{\n searchString: string;\n location: string;\n sector: string\n}\n\nconst filters:Filters = {\n searchString: 'cute cats',\n location: '',\n sector: 'education',\n};\n const result = cleanProps(filters as Record<keyof Filters, string>);\nconsole.log(result); // outputs: { searchString: 'cute cats', sector: 'education' }\n\n"
},
{
"answer_id": 74164878,
"author": "Yash Mehta",
"author_id": 14368064,
"author_profile": "https://Stackoverflow.com/users/14368064",
"pm_score": 0,
"selected": false,
"text": "function removeNullValues(obj) {\n // Check weather obj is an array\n if (Array.isArray(obj)) {\n // Creating copy of obj so that index is maintained after splice\n obj.slice(0).forEach((val) => {\n if (val === null) {\n obj.splice(obj.indexOf(val), 1);\n } else if (typeof val === 'object') {\n // Check if array has an object\n removeNullValues(val);\n }\n });\n } else if (typeof obj === 'object') {\n // Check for object\n Object.keys(obj).forEach((key) => {\n if (obj[key] === null) {\n delete obj[key];\n } else if (typeof obj[key] === 'object') {\n removeNullValues(obj[key]);\n }\n });\n }\n return obj;\n}\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33581/"
] |
286,149
|
<p>I'm trying to disable a button when a user submits a payment form and the code to post the form is causing a double post in firefox.
This problem does not occur when the code is removed, and does not occur in any browser other than firefox.</p>
<p>Any idea how to prevent the double post here?</p>
<pre><code>System.Text.StringBuilder sb = new StringBuilder();
sb.Append("if (typeof(Page_ClientValidate) == 'function') { ");
sb.Append("if (Page_ClientValidate() == false) { return false; }} ");
sb.Append("this.value = 'Please wait...';");
sb.Append("this.disabled = true;");
sb.Append(Page.GetPostBackEventReference(btnSubmit ));
sb.Append(";");
btnSubmit.Attributes.Add("onclick", sb.ToString());
</code></pre>
<p>it's the sb.Append(Page.GetPostBackEventReference(btnSubmit )) line that's causing the issue</p>
<p>Thanks</p>
<p>EDIT: Here's the c# of the button:</p>
<pre><code><asp:Button ID="cmdSubmit" runat="server" Text="Submit" />
</code></pre>
<p>here's the html<br><br>
This code posts twice (and disables the submit button and verifies input):</p>
<pre><code><input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" onclick="if (typeof(Page_ClientValidate) == 'function') { if (Page_ClientValidate() == false) { return false; }} this.value = 'Please wait...';this.disabled = true;document.getElementById('ctl00_MainContent_cmdBack').disabled = true;__doPostBack('ctl00$MainContent$cmdSubmit','');" id="ctl00_MainContent_cmdSubmit" />
</code></pre>
<p><br>This code posts twice (but doesn’t disable the submit button):</p>
<pre><code><input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" onclick="__doPostBack('ctl00$MainContent$cmdSubmit','');" id="ctl00_MainContent_cmdSubmit" />
</code></pre>
<p><br>This code posts once (but doesn’t verify the user input and doesn’t disable the submit button):</p>
<pre><code><input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" id="ctl00_MainContent_cmdSubmit" />
</code></pre>
<p><br>This code posts once (but doesn’t disable submit button):</p>
<pre><code><input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$MainContent$cmdSubmit&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="ctl00_MainContent_cmdSubmit" />
</code></pre>
<p>This code doesn’t post at all:
<br><br></p>
<pre><code><input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" onclick="this.disabled = true;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$MainContent$cmdSubmit&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="ctl00_MainContent_cmdSubmit" />
</code></pre>
<p>Obviously it’s the disabling of the submit button that’s posing the problem. Do you have any ideas how we can disable the submit to avoid multiple clicking? </p>
|
[
{
"answer_id": 286154,
"author": "Jeromy Irvine",
"author_id": 8223,
"author_profile": "https://Stackoverflow.com/users/8223",
"pm_score": 2,
"selected": false,
"text": "btnSubmit Page.GetPostBackEventReference Page_Load function disableOnSubmit(target)\n{\n if (typeof(Page_ClientValidate) == 'function') {\n if (Page_ClientValidate() == false) { return false; }\n }\n target.value = 'Please wait...';\n target.disabled = true;\n return true;\n}\n <asp:Button ID=\"cmdSubmit\" runat=\"server\" Text=\"Submit\" onclick=\"btnSumbit_Click\" OnClientClick=\"return disableOnSubmit(this);\" />\n"
},
{
"answer_id": 1910457,
"author": "ta4ka",
"author_id": 232449,
"author_profile": "https://Stackoverflow.com/users/232449",
"pm_score": 0,
"selected": false,
"text": "private void checkButtonDoubleClick(Button button)\n {\n System.Text.StringBuilder sbValid = new System.Text.StringBuilder();\n sbValid.Append(\"if (typeof(Page_ClientValidate) == 'function') { \");\n sbValid.Append(\"if (Page_ClientValidate() == false) { return false; }} \");\n sbValid.Append(\"this.value = 'Please wait...';\");\n sbValid.Append(\"this.disabled = true;\");\n sbValid.Append(this.Page.ClientScript.GetPostBackEventReference(button, \"\"));\n sbValid.Append(\";return false;\");\n button.Attributes.Add(\"onclick\", sbValid.ToString());\n }\n"
},
{
"answer_id": 2544644,
"author": "Clyde",
"author_id": 305029,
"author_profile": "https://Stackoverflow.com/users/305029",
"pm_score": 1,
"selected": false,
"text": "sbValid.Append(this.Page.ClientScript.GetPostBackEventReference(button, \"\")); \nsbValid.Append(\";\");\n sbValid.Append(this.Page.ClientScript.GetPostBackEventReference(button, \"\")); \n sbValid.Append(\";return false;\");\n"
},
{
"answer_id": 24120988,
"author": "fgohil",
"author_id": 1900285,
"author_profile": "https://Stackoverflow.com/users/1900285",
"pm_score": 0,
"selected": false,
"text": "<asp:Button ID=\"cmdSubmit\" runat=\"server\" Text=\"Submit\" onclick=\"btnSumbit_Click\" OnClientClick=\"this.style.display = 'none';\"/>\n <button type=\"button\" class=\"btn btn-primary btn-lg \" id=\"load1\" data-loading-text=\"<i class='fa fa-circle-o-notch fa-spin'></i> Processing Order\">Submit Order</button>\n\n$('.btn').on('click', function() {\n var $this = $(this);\n $this.button('loading');\n setTimeout(function() {\n $this.button('reset');\n }, 8000);\n});\n"
},
{
"answer_id": 31873749,
"author": "joy",
"author_id": 5201325,
"author_profile": "https://Stackoverflow.com/users/5201325",
"pm_score": -1,
"selected": false,
"text": "<asp:Button ID=\"btn\" runat=\"server\" Text=\"something\" onclick=\"btn_Click\" \nValidationGroup=\"V1\" onClientClick=\"if(Page_ClientValidate('V1'))\n{this.disabled=true;this.value='Please Wait....';__doPostBack(this.id);}\n\"UseSubmitBehavior=\"false\" />\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36798/"
] |
286,150
|
<p>So I'm using python to do some parsing of web pages and I want to split the full web address into two parts. Say I have the address <a href="http://www.stackoverflow.com/questions/ask">http://www.stackoverflow.com/questions/ask</a>. I would need the protocol and domain (e.g. <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a>) and the path (e.g. /questions/ask). I figured this might be solved by some regex, however I'm not so handy with that. Any suggestions?</p>
|
[
{
"answer_id": 286155,
"author": "Cybis",
"author_id": 32998,
"author_profile": "https://Stackoverflow.com/users/32998",
"pm_score": -1,
"selected": false,
"text": "import re\nurl = \"http://stackoverflow.com/questions/ask\"\nprotocol, domain = re.match(r\"(http://[^/]*)(.*)\", url).groups()\n"
},
{
"answer_id": 286194,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 4,
"selected": false,
"text": ">>> from urlparse import urlparse\n>>>\n>>> parts = urlparse(\"http://www.stackoverflow.com/questions/ask\")\n>>> parts.scheme + \"://\" + parts.netloc\n'http://www.stackoverflow.com'\n>>> parts.path\n'/questions/ask'\n from urllib.parse import urlparse"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] |
286,161
|
<p>example:</p>
<p>I want to see if <code>array[5]</code> holds a value or is empty.</p>
|
[
{
"answer_id": 286163,
"author": "Rob Kennedy",
"author_id": 33732,
"author_profile": "https://Stackoverflow.com/users/33732",
"pm_score": 3,
"selected": false,
"text": "Object null"
},
{
"answer_id": 286167,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 6,
"selected": true,
"text": "0 int int [] myArray ;\nmyArray = new int[7] ;\n 0 int[] myArray = { 12, 7, 32, 15, 113, 0, 7 };\n {}"
},
{
"answer_id": 286746,
"author": "Leigh",
"author_id": 26061,
"author_profile": "https://Stackoverflow.com/users/26061",
"pm_score": -1,
"selected": false,
"text": "private static final int EMPTY = -1;\n int[] myArray = new int[size];\nArrays.fill(myArray, EMPTY);\n if (myArray[i] == EMPTY)\n{\n //element i is empty\n}\n"
},
{
"answer_id": 74200153,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 0,
"selected": false,
"text": "Integer[] myArray …\n… Objects.isNull( myArray[ 5 ] ) …\n… Objects.nonNull( myArray[ 5 ] ) …\n int[] Integer[] int 0 Integer[] int[] Integer[] integers = new Integer[ 12 ] ;\nSystem.out.println( Arrays.toString( integers ) ) ;\n null null int Integer integers[ 2 ] = 42 ; // Auto-boxing.\n integers[ 5 ] = Integer.valueOf( 99 ) ; // Unnecessary, because of auto-boxing.\n System.out.println( Arrays.toString( integers ) ) ;\n null array[5] null boolean slotAtIndex5HoldsObjectRef = ( null != integers[ 5 ] ) ; // Parens are not necessary, but improve readability.\n Objects boolean slot5Filled = Objects.nonNull( integers[ 5 ] ) ;\n Integer x = Objects.requireNonNullElse( integers[ 5 ] , Integer.valueOf( 101 ) ) ;\n Integer y = Objects.requireNonNullElse( integers[ 7 ] , Integer.valueOf( 101 ) ) ;\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36545/"
] |
286,184
|
<p>I have a c# winforms program and it opens up a serial port. The problem happens when the end user unplugs the usb cable and then the device disappears. After this the program will crash and want to report the error to microsoft. </p>
<p>Is there a way to capture this event and shut down gracefully? </p>
|
[
{
"answer_id": 1327400,
"author": "MrHIDEn",
"author_id": 160581,
"author_profile": "https://Stackoverflow.com/users/160581",
"pm_score": 2,
"selected": false,
"text": "Windows Registry Editor Version 5.00\nHKEY_LOCAL_MACHINE\\HARDWARE\\DEVICEMAP\\SERIALCOMM]\n\"Winachsf0\"=\"COM10\"\n\"\\\\Device\\\\mxuport0\"=\"COM1\"\n\"\\\\Device\\\\Serial2\"=\"COM13\"\n"
},
{
"answer_id": 5270224,
"author": "Fun Mun Pieng",
"author_id": 2191695,
"author_profile": "https://Stackoverflow.com/users/2191695",
"pm_score": 1,
"selected": false,
"text": "ErrorReceived private void buttonStart_Click(object sender, EventArgs e)\n{\n port.ErrorReceived += new System.IO.Ports.SerialErrorReceivedEventHandler(port_ErrorReceived);\n}\n\nvoid port_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)\n{\n // TODO: handle the problem here\n}\n string[] ports = System.IO.Ports.SerialPort.GetPortNames();\nif (ports.Contains(\"COM7:\"))\n{\n // TODO: Can continue\n}\nelse\n{\n // TODO: Cannot, terminate properly\n}\n try-catch"
},
{
"answer_id": 5281396,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 4,
"selected": true,
"text": "using System;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\nusing System.Management;\nclass UsbWatcher \n{\n public static void Main() \n {\n WMIEvent wEvent = new WMIEvent();\n ManagementEventWatcher watcher = null;\n WqlEventQuery query;\n ManagementOperationObserver observer = new ManagementOperationObserver();\n\n ManagementScope scope = new ManagementScope(\"root\\\\CIMV2\");\n scope.Options.EnablePrivileges = true; \n try \n {\n query = new WqlEventQuery();\n query.EventClassName = \"__InstanceCreationEvent\";\n query.WithinInterval = new TimeSpan(0,0,10);\n\n query.Condition = @\"TargetInstance ISA 'Win32_USBControllerDevice' \";\n watcher = new ManagementEventWatcher(scope, query);\n\n watcher.EventArrived \n += new EventArrivedEventHandler(wEvent.UsbEventArrived);\n watcher.Start();\n }\n catch (Exception e)\n {\n //handle exception\n }\n}\n protected virtual void OnUsbConnected(object Sender, EventArrivedEventArgs Arguments)\n{\n PropertyData TargetInstanceData = Arguments.NewEvent.Properties[\"TargetInstance\"];\n\n if (TargetInstanceData != null)\n {\n ManagementBaseObject TargetInstanceObject = (ManagementBaseObject)TargetInstanceData.Value;\n if (TargetInstanceObject != null)\n {\n string dependent = TargetInstanceObject.Properties[\"Dependent\"].Value.ToString();\n string deviceId = dependent.Substring(dependent.IndexOf(\"DeviceID=\") + 10);\n\n // device id string taken from windows device manager\n if (deviceId = \"USB\\\\\\\\VID_0403&PID_6001\\\\\\\\12345678\\\"\")\n {\n // Device is connected\n }\n }\n }\n}\n"
},
{
"answer_id": 21564661,
"author": "jegan",
"author_id": 1857677,
"author_profile": "https://Stackoverflow.com/users/1857677",
"pm_score": 2,
"selected": false,
"text": "'Win32_USBControllerDevice' 'Win32_PnPEntity' Description using System;\nusing System.ComponentModel.Composition;\nusing System.Management;\n\npublic class UsbDeviceMonitor\n{\n private ManagementEventWatcher plugInWatcher;\n private ManagementEventWatcher unPlugWatcher;\n private const string MyDeviceDescription = @\"My Device Description\";\n\n ~UsbDeviceMonitor()\n {\n Dispose();\n }\n\n public void Dispose()\n {\n if (plugInWatcher != null)\n try\n {\n plugInWatcher.Dispose();\n plugInWatcher = null;\n }\n catch (Exception) { }\n\n if (unPlugWatcher == null) return;\n try\n {\n unPlugWatcher.Dispose();\n unPlugWatcher = null;\n }\n catch (Exception) { }\n }\n\n public void Start()\n {\n const string plugInSql = \"SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_PnPEntity'\";\n const string unpluggedSql = \"SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_PnPEntity'\";\n\n var scope = new ManagementScope(\"root\\\\CIMV2\") {Options = {EnablePrivileges = true}};\n\n var pluggedInQuery = new WqlEventQuery(plugInSql);\n plugInWatcher = new ManagementEventWatcher(scope, pluggedInQuery);\n plugInWatcher.EventArrived += HandlePluggedInEvent;\n plugInWatcher.Start();\n\n var unPluggedQuery = new WqlEventQuery(unpluggedSql);\n unPlugWatcher = new ManagementEventWatcher(scope, unPluggedQuery);\n unPlugWatcher.EventArrived += HandleUnPluggedEvent;\n unPlugWatcher.Start();\n }\n\n private void HandleUnPluggedEvent(object sender, EventArrivedEventArgs e)\n {\n var description = GetDeviceDescription(e.NewEvent);\n if (description.Equals(MyDeviceDescription))\n // Take actions here when the device is unplugged\n }\n\n private void HandlePluggedInEvent(object sender, EventArrivedEventArgs e)\n {\n var description = GetDeviceDescription(e.NewEvent);\n if (description.Equals(MyDeviceDescription))\n // Take actions here when the device is plugged in\n }\n\n private static string GetDeviceDescription(ManagementBaseObject newEvent)\n {\n var targetInstanceData = newEvent.Properties[\"TargetInstance\"];\n var targetInstanceObject = (ManagementBaseObject) targetInstanceData.Value;\n if (targetInstanceObject == null) return \"\";\n\n var description = targetInstanceObject.Properties[\"Description\"].Value.ToString();\n return description;\n }\n}\n 'Win32_PnPEntity' __InstanceCreationEvent __InstanceDeletionEvent"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32958/"
] |
286,187
|
<p>I'm developing an object-oriented PHP website right now and am trying to determine the best way to abstract database functionality from the rest of the system. Right now, I've got a DB class that manages all the connections and queries that the system uses (it's pretty much an interface to MDB2). However, when using this system, I've realized that I've got a lot of SQL query strings showing up everywhere in my code. For instance, in my User class, I've got something like this:</p>
<pre><code>function checkLogin($email,$password,$remember=false){
$password = $this->__encrypt($password);
$query = "SELECT uid FROM Users WHERE email=? AND pw=?";
$result = $this->db->q($query,array($email,$password));
if(sizeof($result) == 1){
$row = $result->fetchRow(MDB2_FETCHMODE_ASSOC);
$uid = $row['uid'];
}else{
return false;
}
/* Rest of the login script */
}
</code></pre>
<p>What I would like to do is find out the best technique for reducing the amount of inline SQL. I understand that one way to do this would be to write functions within User for each of the queries that User makes use of (something like the following), but that could lead to quite a few functions.</p>
<pre><code>function checkLogin($email,$password,$remember=false){
$password = $this->__encrypt($password);
$uid = $this->do_verify_login_query($email,$password);
/* Rest of the login script */
}
function do_verify_login_query($email,$encpw){
$query = "SELECT uid FROM Users WHERE email=? AND pw=?";
$result = $this->$db->q($query,array($email,$encpw));
if(sizeof($result) == 1){
$row = $result->fetchRow(MDB2_FETCHMODE_ASSOC);
return $row['uid'];
}else{
return false;
}
}
</code></pre>
<p>So...my question. What is the best technique for managing the large amount of queries that a typical database application would use? Would the way I described be the proper way of handling this situation? Or what about registering a list of queries within the DB class and associating with each a unique ID (such as USER_CHECKLOGIN) that is passed into the DB's query function? This method could also help with security, as it would limit the queries that could be run to only those that are registered in this list, but it's one more thing to remember when writing all the class functions. Thoughts?</p>
|
[
{
"answer_id": 287478,
"author": "Dave Sherohman",
"author_id": 18914,
"author_profile": "https://Stackoverflow.com/users/18914",
"pm_score": 2,
"selected": false,
"text": "$user->check_password($entered_password) check_password check_password"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33212/"
] |
286,190
|
<p>My present contract engagement is at a large E-Commerce company. Their code base which has origins going back to .Net 1.0 has caught me by surprise to contain many issues that raise the level of smell beyond the last crap I took. </p>
<p>That notwithstanding and trying to diffuse my level of distraction from it, I go along merrily trying to add in features to either fix other problems or extend more crap. Where I touch the DAL/BLL the time it will take to fix the aforementioned will be done. However I wanted to get a vote of confidence from the experts to get some assurance of not wasting the clients time or worse having my credibility voted down by touching "stuff that works". Of course unit testing would solve or at least soften this worry. Perhaps this should also be added to the wtf.com?</p>
<pre><code>Public Function GetSizeInfoBySite(ByVal siteID As String) As IList
Dim strSQL As String = "YES INLINE SQL!! :)"
Dim ci As CrapInfo
Dim alAnArrayList As ArrayList
Dim cn As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim cmd As New SqlCommand(strSQL, cn)
cmd.Parameters.Add(New SqlParameter("@MySiteID", SqlDbType.NVarChar, 2)).Value = siteID
cn.Open()
Dim rs As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
While rs.Read()
ci = New CategoryInfo(rs("someID"), rs("someName"))
If IsNothing(alAnArrayList) Then
alAnArrayList = New ArrayList
End If
alAnArrayList.Add(ci)
End While
rs.Close()
Return CType(alAnArrayList, IList)
End Function
</code></pre>
<p>Does anyone see problems with this aside from the inline SQL which makes my gut churn? At the least wouldn't you ordinarily wrap the above in a try/catch/finally which most of us knows has been around since .Net v1.0? Even better would'nt it be wise to fix with Using statements? Does the SQLDataReader close really encapsulate the connection close automagically? </p>
|
[
{
"answer_id": 286217,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": true,
"text": "List<T>"
},
{
"answer_id": 286244,
"author": "hwiechers",
"author_id": 5883,
"author_profile": "https://Stackoverflow.com/users/5883",
"pm_score": 2,
"selected": false,
"text": "Dim rs As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)\n"
},
{
"answer_id": 287202,
"author": "JohnL",
"author_id": 4814,
"author_profile": "https://Stackoverflow.com/users/4814",
"pm_score": 1,
"selected": false,
"text": "Public Function GetSomeInfoByBusObject(ByVal SomeID As String) As IList\nDim strSQL As String = \"InLine SQL\"\nDim ci As BusObject\nDim list As New GenList(Of BusObject)\nDim cn As New SqlConnection(\n ConfigurationSettings.AppSettings(\"ConnectionString\"))\nUsing cn\n Dim cmd As New SqlCommand(strSQL, cn)\n Using cmd\n cmd.Parameters.Add(New SqlParameter\n (\"@SomeID\", SqlDbType.NVarChar, 2)).Value = strSiteID\n cn.Open()\n Dim result As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)\n While result.Read()\n ci = New BusObject(rs(\"id), result(\"description\"))\n list.Add(DirectCast(ci, BusObject))\n End While\n result.Close()\n End Using\n Return list\nEnd Using\n Public Class GenList(Of T)\n Inherits CollectionBase\n Public Function Add(ByVal value As T) As Integer\n Return List.Add(value)\n End Function\n Public Sub Remove(ByVal value As T)\n List.Remove(value)\n End Sub\n Public ReadOnly Property Item(ByVal index As Integer) As T\n Get\n Return CType(List.Item(index), T)\n End Get\n End Property\nEnd Class\n"
},
{
"answer_id": 885829,
"author": "CRice",
"author_id": 55693,
"author_profile": "https://Stackoverflow.com/users/55693",
"pm_score": 0,
"selected": false,
"text": "Public Function GetSizeInfoBySite(ByVal siteID As String) As IList(Of CategoryInfo)\n Dim strSQL As String = \"YES INLINE SQL!! :)\"\n\n 'reference the 2.0 System.Configuration, and add a connection string section to web.config\n ' <connectionStrings>\n ' <add name=\"somename\" connectionString=\"someconnectionstring\" />\n ' </connectionStrings >\n\n Using cn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings(\"somename\").ConnectionString\n\n Using cmd As New SqlCommand(strSQL, cn)\n\n cmd.Parameters.Add(New SqlParameter(\"@MySiteID\", SqlDbType.NVarChar, 2)).Value = siteID\n cn.Open()\n\n Using reader As IDataReader = cmd.ExecuteReader()\n\n Dim records As IList(Of CategoryInfo) = New List(Of CategoryInfo)\n\n 'get ordinal col indexes\n Dim ordinal_SomeId As Integer = reader.GetOrdinal(\"someID\")\n Dim ordinal_SomeName As Integer = reader.GetOrdinal(\"someName\")\n\n While reader.Read()\n Dim ci As CategoryInfo = New CategoryInfo(reader.GetInt32(ordinal_SomeId), reader.GetString(ordinal_SomeName))\n records.Add(ci)\n End While\n\n Return records\n\n End Using\n End Using\n End Using\n End Function\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4814/"
] |
286,191
|
<p>I have this query statement and want to only get records that has a certain column empty (<code>volunteers_2009.venue_id</code>)</p>
<p>Table is <code>volunteers_2009</code>, column I am looking to see if it is empty: <code>venue_id</code></p>
<p>Here is the current query:</p>
<pre><code>SELECT volunteers_2009.id, volunteers_2009.comments,
volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3,
volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id,
venues.venue_name
FROM volunteers_2009 AS volunteers_2009
LEFT OUTER JOIN venues ON (volunteers_2009.venue_id = venues.id)
ORDER by $order $sort
</code></pre>
<p>I am trying to do this:</p>
<pre><code>SELECT volunteers_2009.id, volunteers_2009.comments,
volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3,
volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id,
venues.venue_name
FROM volunteers_2009 AS volunteers_2009
LEFT OUTER JOIN venues ON (volunteers_2009.venue_id = venues.id)
ORDER by $order $sort
WHERE volunteers_2009.venue_id == ''
</code></pre>
<p>How would I only list records that have an empty column (<code>venue_id</code>) within the table (<code>volunteers_2009</code>)?</p>
|
[
{
"answer_id": 286201,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": false,
"text": "venue_id is WHERE volunteers_2009.venue_id is null\n"
},
{
"answer_id": 286215,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": true,
"text": "SELECT volunteers_2009.id, volunteers_2009.comments, \n volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, \n volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, \n venues.venue_name \nFROM volunteers_2009 \nLEFT JOIN venues ON venue_id = venues.id\nWHERE venues.id IS NULL\nORDER BY $order $sort\n SELECT volunteers_2009.id, volunteers_2009.comments, \n volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, \n volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, \n venues.venue_name \nFROM venues\nLEFT JOIN volunteers_2009 ON volunteers_2009.venue_id = venues.id\nWHERE volunteers_2009.venue_id IS NULL\nORDER BY $order $sort\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26130/"
] |
286,206
|
<p>I'm writing an app for Blackberry that was originally implemented in standard J2ME. The network connection was done using <code>Connector.open("socket://...:80/...")</code> instead of <code>http://</code></p>
<p>Now, I've implemented the connection using both methods, and it seems like some times, the socket method is more responsive, and some times it doesn't work at all. Is there a significant difference between the two? Mostly what I'm trying to achieve is responsiveness from the connection to get a smooth progress bar.</p>
|
[
{
"answer_id": 286933,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 4,
"selected": true,
"text": "http https socket TCP socket deviceside=true deviceside=false http"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36007/"
] |
286,207
|
<p>I am showing an addressbook view to the user and letting them click on a contact and select a phone number. If they select a phone number, I want to get the phone number as an integer and the contact's name as an NSString. </p>
<p>I've tried doing it with the following code: </p>
<pre><code> //printf("%s\n",[[(NSArray *)ABMultiValueCopyArrayOfAllValues(theProperty) objectAtIndex:identifier] UTF8String]);
//CFArrayRef *arrayString = [[(NSArray *)ABMultiValueCopyArrayOfAllValues(theProperty) objectAtIndex:identifier] UTF8String];
NSArray *arrayString = [(NSArray *)ABMultiValueCopyArrayOfAllValues(theProperty) objectAtIndex:identifier];
printf("%s\n", arrayString);
</code></pre>
<p>This code is inside this method:</p>
<pre><code>- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
</code></pre>
<p>And I am checking if the user selected a phone number with this code:</p>
<pre><code>if (propertyType == kABStringPropertyType)
{
[self wrongSelection];
}
else if (propertyType == kABIntegerPropertyType)
{
[self wrongSelection];
}
else if (propertyType == kABRealPropertyType)
{
[self wrongSelection];
}
else if (propertyType == kABMultiStringPropertyType)
{
//This is the phone number...
</code></pre>
<p>I am able to get the phone number to display in the console with printf, however I can't figure out how to convert it into an integer and how to also get the contacts name even though the property selected is not a person's name. </p>
<p>Also, what I'm doing seems very inefficient. Are there any better ways to do this?</p>
<p>Edit: If I can't store them as an int, a string would be fine. I just can't figure out how to go from that array to an actual string. If I cast it or save it as a UTF8String I always get some error. </p>
|
[
{
"answer_id": 286281,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 4,
"selected": false,
"text": "switch( propertyType ) {\n case kABMultiStringPropertyType:\n // this is the phone number, do something\n break;\n default:\n [self wrongSelection];\n break;\n}\n ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(person, kABPersonPhoneProperty);\nNSArray* phoneNumbers = (NSArray*)ABMultiValueCopyArrayOfAllValues(phoneNumberProperty);\nCFRelease(phoneNUmberProperty);\n\n// Do whatever you want with the phone numbers\nNSLog(@\"Phone numbers = %@\", phoneNumbers);\n[phoneNumbers release];\n"
},
{
"answer_id": 287241,
"author": "Ed Marty",
"author_id": 36007,
"author_profile": "https://Stackoverflow.com/users/36007",
"pm_score": 2,
"selected": false,
"text": "CFStringRef cfName = ABRecordCopyCompositeName(person);\nNSString *personName = [NSString stringWithString:(NSString *)cfName];\nCFRelease(cfName);\n\nABMultiValueRef container = ABRecordCopyValue(person, property);\nCFStringRef contactData = ABMultiValueCopyValueAtIndex(container, identifier);\nCFRelease(container);\nNSString *contactString = [NSString stringWithString:(NSString *)contactData];\nCFRelease(contactData);\n contactString personName"
},
{
"answer_id": 8136033,
"author": "nfriese",
"author_id": 737872,
"author_profile": "https://Stackoverflow.com/users/737872",
"pm_score": 0,
"selected": false,
"text": "CFStringRef cfName = ABRecordCopyCompositeName(person);\nNSString *personName = [NSString stringWithString:(NSString *)cfName];\nCFRelease(cfName); \n NSString *personName = nil;\nif ((cfName = ABRecordCopyCompositeName(person)) != nil) {\n personName = [NSString stringWithString:(NSString *)cfName];\n CFRelease(cfName); \n}\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23695/"
] |
286,219
|
<p>I'm trying to run a freshly created ASP.NET Website using C#, however when I do so it launches FireFox and attempts to connect to <a href="http://localhost:1295/WebSite1/Default.aspx" rel="nofollow noreferrer">http://localhost:1295/WebSite1/Default.aspx</a> (for example), but after about 10-15 seconds it displays a "Connection Interrupted - The connection to the server was reset while the page was loading." Error.</p>
<p>This issue is also present with older ASP.NET C# pages/Web Services I've built in the past, nothing is actually running off the ASP.NET Development server.</p>
<p>I am using: Windows XP Pro SP2, Visual Studio 2008</p>
<p>For reference I have SQL Server 2005 Developer Edition installed as well.</p>
<p>I have tried:</p>
<ul>
<li>Browsing it with IE instead of Mozilla</li>
<li>Trying 2.0 framework instead of 3.5</li>
<li>Reinstalling Visual Studio 2008</li>
</ul>
<p>This problem seems so trivial the more I think about it, but I havn't been able to work it out just yet! Appreciate any help on the matter.</p>
|
[
{
"answer_id": 5347747,
"author": "JollySwagman",
"author_id": 633298,
"author_profile": "https://Stackoverflow.com/users/633298",
"pm_score": 3,
"selected": false,
"text": "System.Web.HttpException (0x80004005): Maximum request length exceeded.\n <system.web>\n <httpRuntime maxRequestLength=\"65535\" />\n</system.web>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30598/"
] |
286,238
|
<p>is it possible to throw a custom error message to a ThrowActivity, in windows workflow foundation?</p>
<p>eg. Imagine i want to throw this exception, in my WF :-</p>
<pre><code>CutomException("This is my custom error message", myNumber, myObect);
</code></pre>
<p>cheers :)</p>
|
[
{
"answer_id": 287159,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 3,
"selected": true,
"text": "Fault ThrowActivity throwActivity1.Fault = new CustomException(\"This is my custom error message\", myNumber, myObect);\n"
},
{
"answer_id": 364703,
"author": "balaweblog",
"author_id": 22162,
"author_profile": "https://Stackoverflow.com/users/22162",
"pm_score": 1,
"selected": false,
"text": " public DiscontinuedProductException(string message)\n : base(message)\n {\n }\n\n public DiscontinuedProductException(string message, Exception innerException)\n : base(message, innerException)\n {\n }\n\n protected DiscontinuedProductException(SerializationInfo info, StreamingContext context)\n : base(info, context)\n {\n }\n}\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
286,250
|
<p>If I am evaluating two variables and not two method calls does it matter weather I use "&&" or "&"</p>
<pre><code>//some logic that sets bool values
boolean X = true;
boolean Y = true;
if (X & Y){
// perform some operation
}
if (X && Y){
// perform some operation
}
</code></pre>
<p>Further a book I am using for C# 3.0 / .NET 3.5 only makes reference to the && operator, is the & operator going away?</p>
|
[
{
"answer_id": 286258,
"author": "vfilby",
"author_id": 24279,
"author_profile": "https://Stackoverflow.com/users/24279",
"pm_score": 3,
"selected": false,
"text": "true && true == true\n 00101001 & 00100001 = 00100001\n"
},
{
"answer_id": 286259,
"author": "jpoh",
"author_id": 4368,
"author_profile": "https://Stackoverflow.com/users/4368",
"pm_score": 1,
"selected": false,
"text": "int a = 1;\nint b = 2;\nassert (a & b == 0) \nassert (a && b == true) \n"
},
{
"answer_id": 286265,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 3,
"selected": false,
"text": "bool b = obj != null & obj.IsActive\n bool b = obj != null && obj.IsActive\n bool b = obj.IsActive && obj.SetActive(false);\nbool b = obj.IsActive & obj.SetActive(false);\n"
},
{
"answer_id": 286314,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "& & && [Flags]\nenum SomeEnum { // formatted for space...\n None = 0, Foo = 1, Bar = 2 // 4, 8, 16, 32, ...\n}\nstatic void Main() {\n SomeEnum value = GetFlags();\n bool hasFoo = (value & SomeEnum.Foo) != 0;\n}\nstatic SomeEnum GetFlags() { ... }\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35585/"
] |
286,257
|
<p>I am currently refactoring an application that prints its status to the console window. At the moment I am doing something like this:</p>
<pre><code> Console.Write("Print some status.....")
//some code
Console.WriteLine("Done!")
</code></pre>
<p>Now while this works fine, all the logic is hidden between console.writelines and I find makes it very hard to read.</p>
<p>I don't know if there is a better way of doing this, but I just wanted to ask and see if anyone has come up with a better/more clean way of print application status to the console.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 288836,
"author": "Jamie Penney",
"author_id": 68230,
"author_profile": "https://Stackoverflow.com/users/68230",
"pm_score": 1,
"selected": false,
"text": "log4net.Config.BasicConfigurator.Configure(new log4net.Appender.ConsoleAppender());\n private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof (MyClass));\n log.Debug(\"Print Some status ...\");\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6335/"
] |
286,270
|
<p>What is the best way to password protect quicktime streaming videos using php/.htaccess. They are being streamed using rtsp, but I can use other formats if necessary.</p>
<p>I know how to do authentication with php, but I'm not sure how to setup authentication so that will protect the streaming files urls so that a user can't just copy the url and share it.</p>
<p>Or am I overthinking this and I can just use a normal authentication scheme and place the files in a protected directory?</p>
|
[
{
"answer_id": 286307,
"author": "cmptrgeekken",
"author_id": 33212,
"author_profile": "https://Stackoverflow.com/users/33212",
"pm_score": 0,
"selected": false,
"text": "RewriteEngine On\nRewriteCond %{HTTP_REFERER} !^$\nRewriteCond %{HTTP_COOKIE} obscurename=obscurevalue [NC]\nRewriteCond %{HTTP_REFERER} !^http://(www\\.)?yourdomain.com/.*$ [NC]\nRewriteRule \\.(asx¦ASX)$ http://www.yourdomain.com/images/leech.gif [R,L]\n <?php\n // You could also check some sort of session variable\n // that is set when the user visits another part of your\n // site\n if(!isLoggedIn()){\n header(\"Location: errorPage.htm\");\n exit;\n }else{\n // Get the name of the file specified\n $file = get_file_name($_GET['fileID']);\n\n // Specify the proper mime-type for the data you're sending\n // (this may have to change, depending on your situation)\n header(\"Content-type: video/vnd.rn-realvideo\");\n\n // Read the file and output it to the browser\n readfile($file);\n }\n?>\n"
},
{
"answer_id": 286887,
"author": "Josh",
"author_id": 10902,
"author_profile": "https://Stackoverflow.com/users/10902",
"pm_score": 3,
"selected": false,
"text": "if (check_user_can_access()){\n header('X-sendfile: /path/to/file');\n} else {\n header('HTTP/1.1 403 Fail!');\n}\n"
},
{
"answer_id": 286909,
"author": "Jacco",
"author_id": 22674,
"author_profile": "https://Stackoverflow.com/users/22674",
"pm_score": 1,
"selected": false,
"text": "checkCredentials.php <?php\nif ( isAuthorised($_POST['user'], $_POST['pass']) ) {\n header(\"X-Sendfile: $somefile\");\n header(\"Content-Type: application/octet-stream\");\n header(\"Content-Disposition: attachment; file=\\\"$somefile\\\"\");\n exit(0);\n} else {\n show403('bad credentials');\n}\n?>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
286,274
|
<p>Given two 3D vectors A and B, I need to derive a rotation matrix which rotates from A to B.</p>
<p>This is what I came up with:</p>
<ol>
<li>Derive cosine from <strike>acos</strike>(A . B)</li>
<li>Derive sine from <strike>asin</strike>(|A x B| / (|A| * |B|))</li>
<li>Use A x B as axis of rotation</li>
<li>Use matrix given near the bottom of <a href="http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToMatrix/index.htm" rel="nofollow noreferrer">this page</a> (axis angle)</li>
</ol>
<p>This works fine except for rotations of 0° (which I ignore) and 180° (which I treat as a special case). Is there a more graceful way to do this using the Direct3D library? I am looking for a Direct3D specific answer.</p>
<p>Edit: Removed acos and asin (see <a href="https://stackoverflow.com/questions/286274/direct3d-geometry-rotation-matrix-from-two-vectors#286300">Hugh Allen's post</a>)</p>
|
[
{
"answer_id": 286299,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "D3DXMatrixRotationAxis()"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45603/"
] |
286,275
|
<p>What's the best way (if any) to make an image appear "grayed out" with CSS (i.e., without loading a separate, grayed out version of the image)?</p>
<p>My context is that I have rows in a table that all have buttons in the right most cell and some rows need to look lighter than others. So I can make the font lighter easily of course but I'd also like to make the images lighter without having to manage two versions of each image.</p>
|
[
{
"answer_id": 286279,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 9,
"selected": true,
"text": "<div> <div id=\"wrapper\">\n <img id=\"myImage\" src=\"something.jpg\" />\n</div>\n #myImage {\n opacity: 0.4;\n filter: alpha(opacity=40); /* msie */\n}\n\n/* or */\n\n#wrapper {\n opacity: 0.4;\n filter: alpha(opacity=40); /* msie */\n background-color: #000;\n}\n"
},
{
"answer_id": 286305,
"author": "Dave Jensen",
"author_id": 35341,
"author_profile": "https://Stackoverflow.com/users/35341",
"pm_score": 2,
"selected": false,
"text": "<style>\n#color {\n background-color: red;\n float: left;\n}#opacity {\n opacity : 0.4;\n filter: alpha(opacity=40); \n}\n</style>\n\n<div id=\"color\">\n <div id=\"opacity\">\n <img src=\"image.jpg\" />\n </div>\n</div>\n"
},
{
"answer_id": 288532,
"author": "alexmeia",
"author_id": 36587,
"author_profile": "https://Stackoverflow.com/users/36587",
"pm_score": 5,
"selected": false,
"text": "img.lessOpacity { \n opacity: 0.4;\n filter: alpha(opacity=40);\n zoom: 1; /* needed to trigger \"hasLayout\" in IE if no width or height is set */ \n}\n"
},
{
"answer_id": 291296,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 5,
"selected": false,
"text": "jQuery(selector).fadeTo(speed, opacity);\n"
},
{
"answer_id": 4039593,
"author": "OsamaBinLogin",
"author_id": 489632,
"author_profile": "https://Stackoverflow.com/users/489632",
"pm_score": 1,
"selected": false,
"text": "rgba() rgb() style='background-color: rgba(128,128,128, 0.7); rgb(128,128,128)"
},
{
"answer_id": 11842712,
"author": "nmsdvid",
"author_id": 599880,
"author_profile": "https://Stackoverflow.com/users/599880",
"pm_score": 8,
"selected": false,
"text": "img {\n -webkit-filter: grayscale(100%);\n -moz-filter: grayscale(100%);\n -o-filter: grayscale(100%);\n -ms-filter: grayscale(100%);\n filter: grayscale(100%); \n}\n"
},
{
"answer_id": 13909292,
"author": "Sakata Gintoki",
"author_id": 1852300,
"author_profile": "https://Stackoverflow.com/users/1852300",
"pm_score": 6,
"selected": false,
"text": "<a href=\"#\"><img src=\"img.jpg\" /></a>\n img{\n filter: url(\"data:image/svg+xml;utf8,<svg xmlns=\\'http://www.w3.org/2000/svg\\'><filter id=\\'grayscale\\'><feColorMatrix type=\\'matrix\\' values=\\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\\'/></filter></svg>#grayscale\"); /* Firefox 10+, Firefox on Android */\n filter: grayscale(100%);\n -moz-filter: grayscale(100%);\n -ms-filter: grayscale(100%);\n -o-filter: grayscale(100%);\n filter: gray; /* IE6-9 */\n -webkit-filter: grayscale(100%); /* Chrome 19+, Safari 6+, Safari 6+ iOS */}\n a:hover img{\n filter: url(\"data:image/svg+xml;utf8,<svg xmlns=\\'http://www.w3.org/2000/svg\\'><filter id=\\'grayscale\\'><feColorMatrix type=\\'matrix\\' values=\\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\\'/></filter></svg>#grayscale\");\n filter: grayscale(0%);\n -moz-filter: grayscale(0%);\n -ms-filter: grayscale(0%);\n -o-filter: grayscale(0%);\n filter: none ; /* IE6-9 */\n zoom:1; /* needed to trigger \"hasLayout\" in IE if no width or height is set */\n -webkit-filter: grayscale(0%); /* Chrome 19+, Safari 6+, Safari 6+ iOS */\n }\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=9\">"
},
{
"answer_id": 56421996,
"author": "Константин Ван",
"author_id": 4510033,
"author_profile": "https://Stackoverflow.com/users/4510033",
"pm_score": 3,
"selected": false,
"text": "filter: grayscale(100%);\n @keyframes achromatization {\n 0% {}\n 25% {}\n 75% {filter: grayscale(100%);}\n 100% {filter: grayscale(100%);}\n}\n\np {\n font-size: 5em;\n color: yellow;\n animation: achromatization 2s ease-out infinite alternate;\n}\np:first-of-type {\n background-color: dodgerblue;\n} <p>\n ⚡ Bzzzt!\n</p>\n<p>\n ⚡ Bzzzt!\n</p> filter: contrast(0%);\n @keyframes gray-filling {\n 0% {}\n 25% {}\n 50% {filter: contrast(0%);}\n 60% {filter: contrast(0%);}\n 70% {filter: contrast(0%) brightness(0%) invert(100%);}\n 80% {filter: contrast(0%) brightness(0%) invert(100%);}\n 90% {filter: contrast(0%) brightness(0%);}\n 100% {filter: contrast(0%) brightness(0%);}\n}\n\np {\n font-size: 5em;\n color: yellow;\n animation: gray-filling 5s ease-out infinite alternate;\n}\np:first-of-type {\n background-color: dodgerblue;\n} <p>\n ⚡ Bzzzt!\n</p>\n<p>\n ⚡ Bzzzt!\n</p>"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26842/"
] |
286,282
|
<p>How can I make cookies in my Flash application using ActionScript 2.0?</p>
|
[
{
"answer_id": 286349,
"author": "chews",
"author_id": 33966,
"author_profile": "https://Stackoverflow.com/users/33966",
"pm_score": 0,
"selected": false,
"text": "// Javascript Function\nfunction setCookie(c_name,value,expiredays)\n{\n var exdate=new Date();\n exdate.setDate(exdate.getDate()+expiredays);\n document.cookie=c_name+ \"=\" +escape(value)+\n ((expiredays==null) ? \"\" : \";expires=\"+exdate.toGMTString());\n}\n\n// AS2 Function\nmyBtn_btn.onRelease = function(){\n getURL(\"javascript:setCookie('my_cookie','my_value','30')\");\n};\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
286,297
|
<p>I have a suspicion that I'm using the <code>finally</code> block incorrectly, and that I don't understand the fundamentals of its purpose...</p>
<pre><code> function myFunc() {
try {
if (true) {
throw "An error";
}
} catch (e) {
alert (e);
return false;
} finally {
return true;
}
}
</code></pre>
<p>This function will run the <code>catch</code> block, alert "An error", but then return true. Why doesn't it return false?</p>
|
[
{
"answer_id": 286306,
"author": "Gilean",
"author_id": 6305,
"author_profile": "https://Stackoverflow.com/users/6305",
"pm_score": 7,
"selected": true,
"text": "finally true try function myFunc() {\n try {\n if (true) {\n throw \"An error\";\n }\n return true;\n } catch (e) {\n alert (e);\n return false;\n } finally {\n //do cleanup, etc here\n }\n }\n"
},
{
"answer_id": 28165868,
"author": "Danny Mor",
"author_id": 4497780,
"author_profile": "https://Stackoverflow.com/users/4497780",
"pm_score": 1,
"selected": false,
"text": "function getTheFinallyBlockPoint(someValue) {\n var result;\n try {\n if (someValue === 1) {\n throw new Error(\"Don't you know that '1' is not an option here?\");\n }\n result = someValue\n } catch (e) {\n console.log(e.toString());\n throw e;\n } finally {\n console.log(\"I'll write this no matter what!!!\");\n }\n\n return result;\n};\n\ngetTheFinallyBlockPoint(\"I wrote this only because 'someValue' was not 1!!!\");\ngetTheFinallyBlockPoint(1);\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
286,316
|
<p>I authenticate users through Radius, and I have the option to assign Radius attributes through SQL statements, but I can't for the life of me find any documentation on this. Anyone know the proper syntax?</p>
|
[
{
"answer_id": 292110,
"author": "kylex",
"author_id": 36545,
"author_profile": "https://Stackoverflow.com/users/36545",
"pm_score": 2,
"selected": true,
"text": "SELECT 'attribute', value FROM table WHERE username ='$u' SELECT 'Ascend-Data-Rate', hsbrate.rate FROM hsbrate, customer WHERE customer.id = hsbrate.id AND username='$u'"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36545/"
] |
286,321
|
<p>I would like to make my application somewhat REST compliant. I am using Rails on the backend and <a href="https://developers.google.com/web-toolkit/" rel="noreferrer">GWT</a> on the frontend. I would like to do updates and deletes. I realize I can do something like mydomain.com/:id/delete (GET) and accomplish the same thing. However, as I stated previously, I would like to have a REST compliant backend. Thus, I want to do mydomain.com/:id (DELETE) and have it implicitly call my delete method.</p>
<p>Now, it's my understanding that if a browser (my browser is GWT RequestBuilder) doesn't support DELETE/GET, Rails somehow accomplishes this task with a POST and some other url parameter. So, how can I accomplish this with a GWT RequestBuilder?</p>
|
[
{
"answer_id": 286463,
"author": "Christian Lescuyer",
"author_id": 341,
"author_profile": "https://Stackoverflow.com/users/341",
"pm_score": 4,
"selected": true,
"text": "rails jp\ncd jp\n./script/generate scaffold RequestBuilder name:string\nrake db:migrate\n./script/server \n <form action=\"/request_builders\" class=\"new_request_builder\" \n id=\"new_request_builder\" method=\"post\">\n <div style=\"margin:0;padding:0\">\n <input name=\"authenticity_token\" type=\"hidden\" value=\"e76...\" />\n </div>\n <form action=\"/request_builders/1\" class=\"edit_request_builder\" \n id=\"edit_request_builder_1\" method=\"post\">\n <div style=\"margin:0;padding:0\">\n <input name=\"_method\" type=\"hidden\" value=\"put\" />\n <input name=\"authenticity_token\" type=\"hidden\" value=\"e76...\" />\n </div>\n var m = document.createElement('input'); \nm.setAttribute('type', 'hidden'); \nm.setAttribute('name', '_method'); \nm.setAttribute('value', 'delete');\n"
},
{
"answer_id": 6210925,
"author": "clacke",
"author_id": 260122,
"author_profile": "https://Stackoverflow.com/users/260122",
"pm_score": 3,
"selected": false,
"text": "_method=PUT Content-Type x-www-form-urlencoded X-HTTP-Method-Override: PUT"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10333/"
] |
286,332
|
<p>I have subclassed the UITableView control, and the style is grouped, but I do not need the cell separators. I tried setting my table view's separatorStyle to none, but it doesn't work. Can any one help me out?</p>
|
[
{
"answer_id": 456945,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "tableView.separatorStyle = UITableViewCellSeparatorStyleNone;"
},
{
"answer_id": 1661079,
"author": "Akshay Shah",
"author_id": 200931,
"author_profile": "https://Stackoverflow.com/users/200931",
"pm_score": 2,
"selected": false,
"text": "[dayTableView setSeparatorColor:[UIColor whiteColor]]; //or your background color\n"
},
{
"answer_id": 3206569,
"author": "Sam Soffes",
"author_id": 118631,
"author_profile": "https://Stackoverflow.com/users/118631",
"pm_score": 7,
"selected": false,
"text": "separatorStyle tableView.separatorColor = [UIColor clearColor];\n"
},
{
"answer_id": 13720494,
"author": "Gabriel",
"author_id": 1109715,
"author_profile": "https://Stackoverflow.com/users/1109715",
"pm_score": 3,
"selected": false,
"text": "self.myTableView.separatorColor = [UIColor clearColor];\n self.myTableView.separatorColor = [UIColor clearColor];\nself.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;\n"
},
{
"answer_id": 52786567,
"author": "Noer Cholis",
"author_id": 1286189,
"author_profile": "https://Stackoverflow.com/users/1286189",
"pm_score": 2,
"selected": false,
"text": "myTableView.separatorStyle = UITableViewCellSeparatorStyle.none\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
286,334
|
<p>I have a table of events, I need to find all tail events of type 1 and all head events of type 1. </p>
<p>So, for the set of events in this order [1, 1], 3, 1 ,4, 5, [1,1,1] the brackets denote head and tail events of type 1. </p>
<p>This is much better illustrated in SQL:</p>
<pre><code>drop table #event
go
create table #event (group_id int, [date] datetime, [type] int)
create index idx1 on #event (group_id, date)
insert into #event values (1, '2000-01-01', 1)
insert into #event values (1, '2000-01-02', 1)
insert into #event values (1, '2000-01-03', 3)
insert into #event values (1, '2000-01-04', 2)
insert into #event values (1, '2000-01-05', 1)
insert into #event values (2, '2000-01-01', 2)
insert into #event values (2, '2000-01-02', 2)
insert into #event values (2, '2000-01-03', 3)
insert into #event values (2, '2000-01-04', 2)
insert into #event values (2, '2000-01-05', 1)
insert into #event values (3, '2000-01-01', 1)
insert into #event values (3, '2000-01-02', 2)
insert into #event values (3, '2000-01-03', 1)
insert into #event values (3, '2000-01-04', 2)
insert into #event values (3, '2000-01-05', 2)
insert into #event values (4, '2000-01-01', 2)
insert into #event values (4, '2000-01-02', 2)
insert into #event values (4, '2000-01-03', 3)
insert into #event values (4, '2000-01-04', 1)
insert into #event values (4, '2000-01-05', 1)
go
select e1.* from #event e1
where (
not exists (
select top 1 1
from #event e2
where e1.group_id = e2.group_id
and e2.date < e1.date
and e2.type <> 1
) or not exists (
select top 1 1
from #event e2
where e1.group_id = e2.group_id
and e2.date > e1.date
and e2.type <> 1
)
)
and e1.type = 1
</code></pre>
<p>Expected results: </p>
<pre><code>1 2000-01-01 00:00:00.000 1
1 2000-01-02 00:00:00.000 1
1 2000-01-05 00:00:00.000 1
2 2000-01-05 00:00:00.000 1
3 2000-01-01 00:00:00.000 1
4 2000-01-04 00:00:00.000 1
4 2000-01-05 00:00:00.000 1
</code></pre>
<p>This all works just fine and returns my expected results, but it scans through the table 3 times. Is there any way to make this perform faster and reduce the number of table scans? </p>
|
[
{
"answer_id": 286343,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 0,
"selected": false,
"text": ";WITH Ranked AS (\n SELECT \n *,\n Row_Number() OVER (ORDER BY date) as 'rnk'\n FROM #event\n)\n\n\nSELECT * \nFROM Ranked\nWHERE rnk not between \n (SELECT Min(rnk) FROM Ranked r WHERE r.type <> 1 AND ranked.id = r.id)\n AND (SELECT Max(rnk) FROM Ranked r WHERE r.type <> 1 AND ranked.id = r.id)\norder by id\n"
},
{
"answer_id": 286376,
"author": "Dheer",
"author_id": 17266,
"author_profile": "https://Stackoverflow.com/users/17266",
"pm_score": 0,
"selected": false,
"text": "select e1.* from e1 where \ne1.id = 1 and (e1.date <=\n(\nselect min(e2.date) from e2 where\ne2.id <> 1\ngroup by e2.date\n)\nor \n(e1.date >= \nselect max(e3.date) from e3 where\ne3.id <> 1\ngroup by e3.date\n)\n)\n"
},
{
"answer_id": 286446,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 2,
"selected": true,
"text": "declare @i int \nset @i = 10000\nwhile @i > 5 \nbegin\n insert into #event values (@i, '2000-01-01', 1) \n insert into #event values (@i, '2000-01-02', 1) \n insert into #event values (@i, '2000-01-03', 3) \n insert into #event values (@i, '2000-01-04', 2) \n insert into #event values (@i, '2000-01-05', 1) \n set @i = @i -1 \nend \n declare @j int \nset @j = 0 \nwhile @j < 10\nbegin \n set nocount on \n declare @i int \n set @i = 0\n while @i < 10000 \n begin\n insert into #event values (@j, DateAdd(d, @i, '2000-01-01'), rand(10) * 10) \n\n set @i = @i +1 \n end\n set @j = @j + 1 \nend\nset nocount off\n"
},
{
"answer_id": 286832,
"author": "csgero",
"author_id": 21764,
"author_profile": "https://Stackoverflow.com/users/21764",
"pm_score": 0,
"selected": false,
"text": "select distinct e1.* from #event e1 \nleft outer join #event e2 ON \n e1.id = e2.id \n and e2.date < e1.date \n and e2.type <> 1\nleft outer join #event e3 ON\n e1.id = e3.id \n and e3.date > e1.date \n and e3.type <> 1\nwhere e1.type = 1 AND (e2.id is null or e3.id is null)\n"
},
{
"answer_id": 287929,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 0,
"selected": false,
"text": "SELECT DISTINCT e1.* FROM #event e1 \nWHERE e1.type = 1 \n AND \n ( \n NOT EXISTS ( \n SELECT 1 FROM #event \n WHERE type != 1 \n AND id = e1.id \n AND date < e1.date \n ) \n OR NOT EXISTS ( \n SELECT 1 FROM #event \n WHERE type != 1 \n AND id = e1.id \n AND date > e1.date \n ) \n ) \n"
},
{
"answer_id": 288024,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 0,
"selected": false,
"text": "SELECT e1.* FROM event e1 \nWHERE e1.type = 1 \n AND NOT EXISTS \n ( \n SELECT 1 FROM event \n WHERE type != 1 \n AND id = e1.id \n AND date < e1.date \n ) \nUNION ALL\nSELECT e1.* FROM event e1 \nWHERE e1.type = 1 \n AND NOT EXISTS \n ( \n SELECT 1 FROM event \n WHERE type != 1 \n AND id = e1.id \n AND date > e1.date \n ) \n"
},
{
"answer_id": 363436,
"author": "adamant7",
"author_id": 45775,
"author_profile": "https://Stackoverflow.com/users/45775",
"pm_score": 1,
"selected": false,
"text": "select e1.group_id, e1.date, e1.type<br>\nfrom #event e1, #event e2<br>\nwhere e1.type = 1<br>\nand e2.type <> 1<br>\nand e1.group_id= e2.group_id<br>\ngroup by e1.group_id, e1.date, e1.type, e2.group_id<br>\nhaving e1.date < min(e2.date) or e1.date > max(e2.date)\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
] |
286,354
|
<p>I am trying to wrap my head around this. I am making a business specific messaging application, it is going to connect between 5000 and 10,000 machines back to our datacenter via WCF (no vpns, all over the net). It is mainly for alerts and I need to be able to send message direclty to specific clients, and WCF allows me to do all of this with a Duplex contract, but with this many clients it got me thinking about maxing out the TCP port space of 65535 ports.</p>
<p>I am going to assume that all inbound connections are going to come in over whatever port I choose, but outbounds back to the clients are going to take one port each. I am curious if the WCF port sharing service does anything to solve this issue or if its just 65535 ports to an IP address? For that matter, how does MSN Messenger and the like deal with this situation. Granted I may never reach it, but I am getting in the realm at least.</p>
<p>Or does the WCF duplex contract on the service end keep the port open for the callback for the duration of the client, or does it release it?</p>
|
[
{
"answer_id": 286398,
"author": "stephbu",
"author_id": 12702,
"author_profile": "https://Stackoverflow.com/users/12702",
"pm_score": 2,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\n\nTcpTimedWaitDelay = 30\nMaxUserPort = 65534 \nMaxHashTableSize = 65536 \nMaxFreeTcbs = 16000 \n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29466/"
] |
286,375
|
<p>Hi i am encountering problems trying to post a WebRequest under Https. </p>
<p>i received the following errors</p>
<h1>1.-The underlying connection was closed: Unable to connect to the remote server.</h1>
<h1>2.-the operation TimeOut</h1>
<h1>3-The underlying connection was closed: Could not establish secure channel for SSL/TLS.</h1>
<p>i tried with about 3 or 4 different proxies of my company and the customer company and not even when i am directly with the ISP provider with no restrictions, i get the above errors when executing the following method</p>
<pre><code>WebRequest.GetRequestStream()
</code></pre>
<p>this occurs behind a proxy or not, the request can only be succesfully post from one single PC which is behind a proxy. the proxy doesn't have a client certificate installed.</p>
<p>this is under .net framework 1.1 and
the request already contains network credentials.</p>
<p>what could be?</p>
<h1>Update</h1>
<p>the inner exception the 3rd error is the following:
The function completed successfully, but must be called again to complete the context</p>
<p>according to iisper.h <a href="http://doc.ddart.net/msdn/header/include/issperr.h.html" rel="nofollow noreferrer">documentation</a> this error belongs to the </p>
<pre><code>//
// MessageId: SEC_I_CONTINUE_NEEDED
//
// MessageText:
//
// The function completed successfully, but must be called
// again to complete the context
//
#define SEC_I_CONTINUE_NEEDED ((HRESULT)0x00090312L)
</code></pre>
<p>on <a href="http://msdn.microsoft.com/en-us/library/aa375924(VS.85).aspx" rel="nofollow noreferrer">MSDN</a> this refers to </p>
<p>SEC_I_CONTINUE_NEEDED
The client must send the output token to the server and wait for a return token. The returned token is then passed in another call to InitializeSecurityContext (Schannel). The output token can be empty.</p>
<p>does this means the PC lacks a client certificate?</p>
|
[
{
"answer_id": 286393,
"author": "Sani Singh Huttunen",
"author_id": 26742,
"author_profile": "https://Stackoverflow.com/users/26742",
"pm_score": 0,
"selected": false,
"text": "// .NET 2.0+\n...\nServicePointManager.ServerCertificateValidationCallback += MyValidationCallback\n...\npublic bool MyValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors err)\n{\n return true;\n}\n\n// .NET 1.1\npublic class MyCertificatePolicy : ICertificatePolicy\n{\n public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)\n {\n return true;\n }\n}\n...\nServicePointManager.CertificatePolicy = new MyCertificatePolicy();\n...\n"
},
{
"answer_id": 286424,
"author": "Andrew Cox",
"author_id": 27907,
"author_profile": "https://Stackoverflow.com/users/27907",
"pm_score": 1,
"selected": false,
"text": "telnet <domainname> 443\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14440/"
] |
286,392
|
<p>How to use batch file to check if an application still running or not? If the application still running, this process will loop again and again. Else, there will be error message.</p>
<p>Thank you very much</p>
|
[
{
"answer_id": 286453,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "@echo off\n\nCommandYouWillRun.exe\n\nrem waiting for the process to start\n:startcmd\nsleep 1\nc:\\path\\to\\pslist.exe CommandYouWillRun > NUL\nIF ERRORLEVEL 1 goto startcmd\n\nrem the process has now started\n\n:waitforcmd\nsleep 1\nc:\\path\\to\\pslist.exe CommandYouWillRun > NUL\nIF ERRORLEVEL 1 got finished\ngoto waitforcmd\n\n:finished\necho \"This is an error message\"\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
286,399
|
<p>I want to build two-dimentional array of strings where length of one dimention is 2. Similar to this</p>
<pre><code>string[,] array = new string[,]
{
{"a", "b"},
{"c", "d"},
{"e", "f"},
{"g", "h"}
}
</code></pre>
<p>Doing</p>
<pre><code>List<string[]> list = new List<string[]>();
list.Add(new string[2] {"a", "b"});
list.Add(new string[2] {"c", "d"});
list.Add(new string[2] {"e", "f"});
list.Add(new string[2] {"g", "h"});
list.ToArray();
</code></pre>
<p>gives me </p>
<pre><code>string[][]
</code></pre>
<p>but not </p>
<pre><code>string[,]
</code></pre>
<p>array.</p>
<p>Just curious, is there some trick to build dynamically</p>
<pre><code>string[,]
</code></pre>
<p>array somehow?</p>
|
[
{
"answer_id": 286420,
"author": "Andrew Kennan",
"author_id": 22506,
"author_profile": "https://Stackoverflow.com/users/22506",
"pm_score": 0,
"selected": false,
"text": "List<string[]> string[,] string[]"
},
{
"answer_id": 286428,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 2,
"selected": false,
"text": "ToArray() StringTupleCollection ArrayList [x,2] [x][2] List<string[2]> StringTupple public class StringTupple : KeyValuePair<string, string>\n{\n}\n"
},
{
"answer_id": 286445,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "public static T[,] ToRectangularArray<T>(this IEnumerable<T[]> source)\n{\n if (!source.Any())\n {\n return new T[0,0];\n }\n\n int width = source.First().Length;\n if (source.Any(array => array.Length != width))\n {\n throw new ArgumentException(\"All elements must have the same length\");\n }\n\n T[,] ret = new T[source.Count(), width];\n int row = 0;\n foreach (T[] array in source)\n {\n for (int col=0; col < width; col++)\n {\n ret[row, col] = array[col];\n }\n row++;\n }\n return ret;\n}\n IEnumerable<IEnumerable<T>> public static T[,] ToRectangularArray<T,U>(this IEnumerable<U> source)\n where U : IEnumerable<T>\n"
},
{
"answer_id": 10671635,
"author": "Terrence",
"author_id": 1405975,
"author_profile": "https://Stackoverflow.com/users/1405975",
"pm_score": 4,
"selected": false,
"text": "List<KeyValuePair<string, string>>\n"
},
{
"answer_id": 12289885,
"author": "hagensoft",
"author_id": 1608243,
"author_profile": "https://Stackoverflow.com/users/1608243",
"pm_score": 0,
"selected": false,
"text": "foreach (KeyValuePair<string, bool> Role in model.Roles){...}\n"
},
{
"answer_id": 62598372,
"author": "TheJoe",
"author_id": 8412763,
"author_profile": "https://Stackoverflow.com/users/8412763",
"pm_score": 1,
"selected": false,
"text": "private struct XmlPair\n{\n public string Name { set; get; }\n public string Value { set; get; }\n}\n\nList<XmlPair> Pairs = new List<XmlPair>();\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
] |
286,402
|
<p>I have a couple of array's:</p>
<pre><code>const string a_strs[] = {"cr=1", "ag=2", "gnd=U", "prl=12", "av=123", "sz=345", "rc=6", "pc=12345"};
const string b_strs[] = {"cr=2", "sz=345", "ag=10", "gnd=M", "prl=11", "rc=6", "cp=34", "cv=54", "av=654", "ct=77", "pc=12345"};
</code></pre>
<p>which i then need to parse out for '=' and then put the values in the struct. (the rc key maps to the fc key in the struct), which is in the form of:</p>
<pre><code>struct predict_cache_key {
pck() :
av_id(0),
sz_id(0),
cr_id(0),
cp_id(0),
cv_id(0),
ct_id(0),
fc(0),
gnd(0),
ag(0),
pc(0),
prl_id(0)
{ }
int av_id;
int sz_id;
int cr_id;
int cp_id;
int cv_id;
int ct_id;
int fc;
char gnd;
int ag;
int pc;
long prl_id;
};
</code></pre>
<p>The problem I am encountering is that the array's are not in sequence or in the same sequence as the struct fields. So, I need to check each and then come up with a scheme to put the same into the struct.</p>
<p>Any help in using C or C++ to solve the above?</p>
|
[
{
"answer_id": 286450,
"author": "qrdl",
"author_id": 28494,
"author_profile": "https://Stackoverflow.com/users/28494",
"pm_score": 3,
"selected": false,
"text": "key value if-else-if-else ... if (!strcmp(key, \"cr\"))\n my_struct.cr = value;\nelse if (!strcmp(key, \"ag\"))\n my_struct.ag = value;\n...\n #define PROC_KEY_VALUE_PAIR(A) else if (!strcmp(key,#A)) my_struct.##A = value else if (0);\nPROC_KEY_VALUE_PAIR(cr);\nPROC_KEY_VALUE_PAIR(ag);\n...\n _id _id"
},
{
"answer_id": 286667,
"author": "quinmars",
"author_id": 18687,
"author_profile": "https://Stackoverflow.com/users/18687",
"pm_score": 3,
"selected": true,
"text": "const string a_strs[] = {\"cr=1\", \"ag=2\", \"gnd=U\", NULL}; \nbool\nparse_string(const string &str, char *buffer, size_t b_size, int *num)\n{\n char *ptr;\n\n strncpy(buffer, str.c_str(), b_size);\n buffer[b_size - 1] = 0;\n\n /* find the '=' */\n ptr = strchr(buffer, '=');\n\n if (!ptr) return false;\n\n *ptr = '\\0';\n ptr++;\n\n *num = atoi(ptr);\n\n return true;\n}\n \nfor (const string *cur_str = array; *cur_str; cur_str++)\n{\n char key[128];\n int value = 0;\n\n if (!parse_string(*cur_string, key, sizeof(key), &value)\n continue;\n\n /* and here what qrdl suggested */\n if (!strcmp(key, \"cr\")) cr_id = value;\n else if ...\n}\n"
},
{
"answer_id": 286693,
"author": "flolo",
"author_id": 36472,
"author_profile": "https://Stackoverflow.com/users/36472",
"pm_score": 0,
"selected": false,
"text": "const char * wordlist[] = {\"pc\",\"gnd\",\"ag\",\"prl_id\",\"fc\"};\nconst int offsets[] = { offsetof(mystruct, pc), offsetof(mystruct, gnd), offsetof(mystruct, ag), offsetof(mystruct, prl_id), offsetof(mystruct, fc)};\nconst int sizes[] = { sizeof(mystruct.pc), sizeof(mystruct.gnd), sizeof(mystruct.ag), sizeof(mystruct.prl_id), sizeof(mystruct.fc)}\n index = 0;\nwhile (strcmp(wordlist[index], key) && index < 5)\n index++;\nif (index <5)\n memcpy(&mystructvar + offsets[index], &value, sizes[index]);\nelse\n fprintf(stderr, \"Key not valid\\n\"); \n hash=calc_perf_hash(key);\nmemcpy(&mystruct + offsets[hash], &value, sizes[hash]);\n const char * modifier[]={\"%i\",\"%c\", ...\n sscanf(valueString, modifier[hash], &mystructVar + offsets(hash));\n"
},
{
"answer_id": 286820,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 2,
"selected": false,
"text": " const CMemberSetter<predict_cache_key>* setters[] = \n #define SETTER( tag, type, member ) new TSetter<predict_cache_key,type>( #tag, &predict_cache_key::##member )\n { SETTER( \"av\", int, av_id )\n , SETTER( \"sz\", int, sz_id )\n , SETTER( \"cr\", int, cr_id )\n , SETTER( \"cp\", int, cp_id )\n , SETTER( \"cv\", int, cv_id )\n , SETTER( \"ct\", int, ct_id )\n , SETTER( \"fc\", int, fc )\n , SETTER( \"gnd\", char, gnd )\n , SETTER( \"ag\", int, ag )\n , SETTER( \"pc\", int, pc )\n , SETTER( \"prl\", long, prl_id )\n };\n\n PCKFactory<predict_cache_key> factory ( setters );\n\n predict_cache_key a = factory.factor( a_strs );\n predict_cache_key b = factory.factor( b_strs );\n // conversion from key=value pair to \"set the value of a member\"\n // this class merely recognises a key and extracts the value part of the key=value string\n //\n template< typename BaseClass >\n struct CMemberSetter {\n\n const std::string key;\n CMemberSetter( const string& aKey ): key( aKey ){}\n\n bool try_set_value( BaseClass& p, const string& key_value ) const {\n if( key_value.find( key ) == 0 ) {\n size_t value_pos = key_value.find( \"=\" ) + 1;\n action( p, key_value.substr( value_pos ) );\n return true;\n }\n else return false;\n }\n virtual void action( BaseClass& p, const string& value ) const = 0;\n };\n\n // implementation of the action method\n //\n template< typename BaseClass, typename T >\n struct TSetter : public CMemberSetter<BaseClass> {\n typedef T BaseClass::*TMember;\n TMember member;\n\n TSetter( const string& aKey, const TMember t ): CMemberSetter( aKey ), member(t){}\n virtual void action( BaseClass& p, const std::string& valuestring ) const {\n // get value\n T value ();\n stringstream ( valuestring ) >> value;\n (p.*member) = value;\n }\n };\n\n\n template< typename BaseClass >\n struct PCKFactory {\n std::vector<const CMemberSetter<BaseClass>*> aSetters;\n\n template< size_t N >\n PCKFactory( const CMemberSetter<BaseClass>* (&setters)[N] )\n : aSetters( setters, setters+N ) {}\n\n template< size_t N >\n BaseClass factor( const string (&key_value_pairs) [N] ) const {\n BaseClass pck;\n\n // process each key=value pair\n for( const string* pair = key_value_pairs; pair != key_value_pairs + _countof( key_value_pairs); ++pair ) \n {\n std::vector<const CMemberSetter<BaseClass>*>::const_iterator itSetter = aSetters.begin();\n while( itSetter != aSetters.end() ) { // optimalization possible\n if( (*itSetter)->try_set_value( pck, *pair ) )\n break;\n ++itSetter;\n }\n }\n\n return pck;\n }\n };\n"
},
{
"answer_id": 287353,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "/* clients using the above classes derive from lookable_fields */\nstruct predict_cache_key : private lookable_fields<predict_cache_key> {\n predict_cache_key(std::vector<std::string> const& vec) {\n for(std::vector<std::string>::const_iterator it = vec.begin();\n it != vec.end(); ++it) {\n std::size_t i = it->find('=');\n set_member(it->substr(0, i), it->substr(i + 1));\n }\n }\n\n long get_prl() const {\n return prl_id;\n }\n\nprivate:\n\n /* ... and define the members that can be looked up. i've only\n * implemented int, char and long for this answer. */\n BEGIN_FIELDS(predict_cache_key)\n FIELD(av_id);\n FIELD(sz_id);\n FIELD(gnd);\n FIELD(prl_id);\n END_FIELDS()\n\n int av_id;\n int sz_id;\n char gnd;\n long prl_id;\n /* ... */\n};\n\nint main() {\n std::string const a[] = { \"av_id=10\", \"sz_id=10\", \"gnd=c\",\n \"prl_id=1192\" };\n predict_cache_key haha(std::vector<std::string>(a, a + 4));\n}\n template<typename T>\nstruct entry {\n enum type { tchar, tint, tlong } type_name;\n\n /* default ctor, so we can std::map it */\n entry() { }\n\n template<typename R>\n entry(R (T::*ptr)) {\n set_ptr(ptr);\n }\n\n void set_ptr(char (T::*ptr)) {\n type_name = tchar;\n charp = ptr;\n };\n\n void set_ptr(int (T::*ptr)) {\n type_name = tint;\n intp = ptr; \n };\n\n void set_ptr(long (T::*ptr)) {\n type_name = tlong;\n longp = ptr; \n };\n\n union {\n char (T::*charp);\n int (T::*intp);\n long (T::*longp);\n };\n};\n\n#define BEGIN_FIELDS(CLASS) \\\n friend struct lookable_fields<CLASS>; \\\n private: \\\n static void init_fields_() { \\\n typedef CLASS parent_class;\n\n#define FIELD(X) \\\n lookable_fields<parent_class>::entry_map[#X].set_ptr(&parent_class::X)\n\n#define END_FIELDS() \\\n } \n\ntemplate<typename Derived>\nstruct lookable_fields {\nprotected:\n lookable_fields() {\n (void) &initializer; /* instantiate the object */\n }\n\n void set_member(std::string const& member, std::string const& value) {\n typename entry_map_t::iterator it = entry_map.find(member);\n if(it == entry_map.end()) {\n std::ostringstream os;\n os << \"member '\" << member << \"' not found\";\n throw std::invalid_argument(os.str());\n }\n\n Derived * derived = static_cast<Derived*>(this);\n\n std::istringstream ss(value);\n switch(it->second.type_name) {\n case entry_t::tchar: {\n /* convert to char */\n ss >> (derived->*it->second.charp);\n break;\n }\n case entry_t::tint: {\n /* convert to int */\n ss >> (derived->*it->second.intp);\n break;\n }\n case entry_t::tlong: {\n /* convert to long */\n ss >> (derived->*it->second.longp);\n break;\n }\n }\n }\n\n typedef entry<Derived> entry_t;\n typedef std::map<std::string, entry_t> entry_map_t;\n static entry_map_t entry_map;\n\nprivate:\n struct init_helper {\n init_helper() {\n Derived::init_fields_();\n }\n };\n\n /* will call the derived class's static init function */\n static init_helper initializer;\n};\n\ntemplate<typename T> \nstd::map< std::string, entry<T> > lookable_fields<T>::entry_map;\n\ntemplate<typename T> \ntypename lookable_fields<T>::init_helper lookable_fields<T>::initializer;\n &classname::member"
},
{
"answer_id": 287518,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 0,
"selected": false,
"text": "typedef struct {\n const char *fieldName;\n int structOffset;\n int fieldSize;\n} t_fieldDef;\n\ntypedef struct {\n int fieldCount;\n t_fieldDef *defs;\n} t_structLayout;\n\nt_memberDef *GetFieldDefByName(const char *name, t_structLayout *layout)\n{\n t_fieldDef *defs = layout->defs;\n int count = layout->fieldCount;\n for (int i=0; i < count; i++) {\n if (strcmp(name, defs->fieldName) == 0)\n return defs;\n defs++;\n }\n return NULL;\n}\n\n/* meta-circular usage */\nstatic t_fieldDef metaFieldDefs[] = {\n { \"fieldName\", offsetof(t_fieldDef, fieldName), sizeof(const char *) },\n { \"structOffset\", offsetof(t_fieldDef, structOffset), sizeof(int) },\n { \"fieldSize\", offsetof(t_fieldDef, fieldSize), sizeof(int) }\n};\nstatic t_structLayout metaFieldDefLayout =\n { sizeof(metaFieldDefs) / sizeof(t_fieldDef), metaFieldDefs };\n sizeof(mumble) t_fieldDef NULL NULL t_structLayout"
},
{
"answer_id": 1812302,
"author": "israel",
"author_id": 220430,
"author_profile": "https://Stackoverflow.com/users/220430",
"pm_score": 0,
"selected": false,
"text": "error: ISO C++ forbids declaration of ‘map’ with no type\n <map> #include <map>\n\n// a framework\n\ntemplate<typename T>\nstruct entry {\n enum type { tchar, tint, tlong } type_name;\n\n /* default ctor, so we can std::map it */\n entry() { }\n\n template<typename R>\n entry(R (T::*ptr)) {\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35416/"
] |
286,419
|
<p>Is it possible to build a .dmg file (for distributing apps) from a non-Mac platform?
And if yes, how?</p>
|
[
{
"answer_id": 3776463,
"author": "jstck",
"author_id": 88979,
"author_profile": "https://Stackoverflow.com/users/88979",
"pm_score": 5,
"selected": false,
"text": "dd if=/dev/zero of=/tmp/foo.dmg bs=1M count=64\nmkfs.hfsplus -v ThisIsFoo /tmp/foo.dmg\n mount -o loop /tmp/foo.dmg /mnt/foo\n"
},
{
"answer_id": 7553878,
"author": "uckelman",
"author_id": 181106,
"author_profile": "https://Stackoverflow.com/users/181106",
"pm_score": 5,
"selected": false,
"text": "mkdir -p dmgdir/progname.app/Contents/{MacOS,Resources}\n...copy your PkgInfo, Info.plist to Contents...\n...copy your .icns to Resources...\n...copy your other things to where you expect them to go...\ngenisoimage -V progname -D -R -apple -no-pad -o progname.dmg dmgdir \n .DS_Store progname progname.app .background/background.png dmgdir /Applications dmg uncompressed.dmg compressed.dmg\n"
},
{
"answer_id": 17735033,
"author": "name",
"author_id": 2597435,
"author_profile": "https://Stackoverflow.com/users/2597435",
"pm_score": 3,
"selected": false,
"text": "git clone https://github.com/hamstergene/libdmg-hfsplus\ncd libdmg-hfsplus && cmake . && make && cd dmg\n./dmg --help\n dmg:\n genisoimage -D -V \"$(PROJECT) $(VERSION)\" -no-pad -r -apple -o project-$(VERSION)-uncompressed.dmg $(DARWIN_DIR)\n ./dmg dmg project-$(VERSION)-uncompressed.dmg project-$(VERSION).dmg\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15173/"
] |
286,426
|
<p>I have a page P1 loading from site S1 which contains an iframe. That iframe loads a page P2 from another site S2. At some point P2 would like to close the browser window, which contains P1 loaded from S1. Of course, since P2 is loaded from another site, it can't just do parent.close().</p>
<p>I have full control over P1 and P2, so I can add JavaScript code to both P1 and P2 as needed.
Suggestions on how to resolve this?</p>
|
[
{
"answer_id": 286472,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<iframe name = \"frame1\" src = \"http://yoursite\">\n</iframe>\n\n<script type = \"text/javascript\">\n alert(window.frames[\"frame1\"].document);\n</script>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5295/"
] |
286,427
|
<p>Inspired by this <a href="https://stackoverflow.com/questions/283561/extracting-leaf-paths-from-n-ary-tree-in-f">question</a> and <a href="https://stackoverflow.com/questions/283561/extracting-leaf-paths-from-n-ary-tree-in-f#283638">answer</a>, how do I create a generic permutations algorithm in F#? Google doesn't give any useful answers to this.</p>
<p>EDIT: I provide my best answer below, but I suspect that Tomas's is better (certainly shorter!)</p>
|
[
{
"answer_id": 286544,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 1,
"selected": false,
"text": "//mini-extension to List for removing 1 element from a list\nmodule List = \n let remove n lst = List.filter (fun x -> x <> n) lst\n\n//Node type declared outside permutations function allows us to define a pruning filter\ntype Node<'a> =\n | Branch of ('a * Node<'a> seq)\n | Leaf of 'a\n\nlet permutations treefilter lst =\n //Builds a tree representing all possible permutations\n let rec nodeBuilder lst x = //x is the next element to use\n match lst with //lst is all the remaining elements to be permuted\n | [x] -> seq { yield Leaf(x) } //only x left in list -> we are at a leaf\n | h -> //anything else left -> we are at a branch, recurse \n let ilst = List.remove x lst //get new list without i, use this to build subnodes of branch\n seq { yield Branch(x, Seq.map_concat (nodeBuilder ilst) ilst) }\n\n //converts a tree to a list for each leafpath\n let rec pathBuilder pth n = // pth is the accumulated path, n is the current node\n match n with\n | Leaf(i) -> seq { yield List.rev (i :: pth) } //path list is constructed from root to leaf, so have to reverse it\n | Branch(i, nodes) -> Seq.map_concat (pathBuilder (i :: pth)) nodes\n\n let nodes = \n lst //using input list\n |> Seq.map_concat (nodeBuilder lst) //build permutations tree\n |> Seq.choose treefilter //prune tree if necessary\n |> Seq.map_concat (pathBuilder []) //convert to seq of path lists\n\n nodes\n let myfilter n = Some(n) //i.e., don't filter\npermutations myfilter ['A';'B';'C';'D'] \n\n//in this case, I want to 'prune' leading zeros from my list before generating paths\nlet noLeadingZero n = \n match n with\n | Branch(0, _) -> None\n | n -> Some(n)\n\n//Curry myself an int-list permutations function with no leading zeros\nlet noLZperm = permutations noLeadingZero\nnoLZperm [0..9] \n"
},
{
"answer_id": 286821,
"author": "Tomas Petricek",
"author_id": 33518,
"author_profile": "https://Stackoverflow.com/users/33518",
"pm_score": 5,
"selected": true,
"text": "let rec permutations list taken = \n seq { if Set.count taken = List.length list then yield [] else\n for l in list do\n if not (Set.contains l taken) then \n for perm in permutations list (Set.add l taken) do\n yield l::perm }\n permutations [1;2;3] Set.empty;;\n"
},
{
"answer_id": 2184129,
"author": "Johan Kullbom",
"author_id": 72165,
"author_profile": "https://Stackoverflow.com/users/72165",
"pm_score": 4,
"selected": false,
"text": "let rec insertions x = function\n | [] -> [[x]]\n | (y :: ys) as l -> (x::l)::(List.map (fun x -> y::x) (insertions x ys))\n\nlet rec permutations = function\n | [] -> seq [ [] ]\n | x :: xs -> Seq.concat (Seq.map (insertions x) (permutations xs))\n"
},
{
"answer_id": 2636471,
"author": "Holoed",
"author_id": 316376,
"author_profile": "https://Stackoverflow.com/users/316376",
"pm_score": 1,
"selected": false,
"text": "let length = Seq.length\nlet take = Seq.take\nlet skip = Seq.skip\nlet (++) = Seq.append\nlet concat = Seq.concat\nlet map = Seq.map\n\nlet (|Empty|Cons|) (xs:seq<'a>) : Choice<Unit, 'a * seq<'a>> =\n if (Seq.isEmpty xs) then Empty else Cons(Seq.head xs, Seq.skip 1 xs)\n\nlet interleave x ys =\n seq { for i in [0..length ys] ->\n (take i ys) ++ seq [x] ++ (skip i ys) }\n\nlet rec permutations xs =\n match xs with\n | Empty -> seq [seq []]\n | Cons(x,xs) -> concat(map (interleave x) (permutations xs))\n"
},
{
"answer_id": 3180680,
"author": "Stephen Swensen",
"author_id": 236255,
"author_profile": "https://Stackoverflow.com/users/236255",
"pm_score": 2,
"selected": false,
"text": "permutations e f : ('a -> 'a -> int) comparable permute let comparer f = { new System.Collections.Generic.IComparer<'a> with member self.Compare(x,y) = f x y } System.Array.Sort IComparer let permutations f e =\n ///Advances (mutating) perm to the next lexical permutation.\n let permute (perm:'a[]) (f: 'a->'a->int) (comparer:System.Collections.Generic.IComparer<'a>) : bool =\n try\n //Find the longest \"tail\" that is ordered in decreasing order ((s+1)..perm.Length-1).\n //will throw an index out of bounds exception if perm is the last permuation,\n //but will not corrupt perm.\n let rec find i =\n if (f perm.[i] perm.[i-1]) >= 0 then i-1\n else find (i-1)\n let s = find (perm.Length-1)\n let s' = perm.[s]\n\n //Change the number just before the tail (s') to the smallest number bigger than it in the tail (perm.[t]).\n let rec find i imin =\n if i = perm.Length then imin\n elif (f perm.[i] s') > 0 && (f perm.[i] perm.[imin]) < 0 then find (i+1) i\n else find (i+1) imin\n let t = find (s+1) (s+1)\n\n perm.[s] <- perm.[t]\n perm.[t] <- s'\n\n //Sort the tail in increasing order.\n System.Array.Sort(perm, s+1, perm.Length - s - 1, comparer)\n true\n with\n | _ -> false\n\n //permuation sequence expression \n let c = f |> comparer\n let freeze arr = arr |> Array.copy |> Seq.readonly\n seq { let e' = Seq.toArray e\n yield freeze e'\n while permute e' f c do\n yield freeze e' }\n let flip f x y = f y x let permutationsAsc e = permutations compare e\nlet permutationsDesc e = permutations (flip compare) e\n"
},
{
"answer_id": 3550869,
"author": "Emile",
"author_id": 18756,
"author_profile": "https://Stackoverflow.com/users/18756",
"pm_score": 1,
"selected": false,
"text": "let rec insertions pre c post =\n seq {\n if List.length post = 0 then\n yield pre @ [c]\n else\n if List.forall (fun x->x<>c) post then\n yield pre@[c]@post\n yield! insertions (pre@[post.Head]) c post.Tail\n }\n\nlet rec permutations l =\n seq {\n if List.length l = 1 then\n yield l\n else\n let subperms = permutations l.Tail\n for sub in subperms do\n yield! insertions [] l.Head sub\n }\n"
},
{
"answer_id": 56072410,
"author": "gmlion",
"author_id": 5743444,
"author_profile": "https://Stackoverflow.com/users/5743444",
"pm_score": 0,
"selected": false,
"text": "let permutations s =\n let rec perm perms carry rem =\n match rem with\n | [] -> carry::perms\n | l ->\n let li = List.indexed l\n let permutations =\n seq { for ci in li ->\n let (i, c) = ci\n (perm\n perms\n (c::carry)\n (li |> List.filter (fun (index, _) -> i <> index) |> List.map (fun (_, char) -> char))) }\n\n permutations |> Seq.fold List.append []\n perm [] [] s\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11410/"
] |
286,441
|
<pre><code>from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')
setup(
options = {'py2exe': {'bundle_files': 1}},
windows = [{'script': "single.py"}],
zipfile = None,
)
</code></pre>
<p>in this setup file for py2exe where it says single.py is that where I place the name of my program?</p>
|
[
{
"answer_id": 286495,
"author": "Denes Tarjan",
"author_id": 17617,
"author_profile": "https://Stackoverflow.com/users/17617",
"pm_score": 3,
"selected": false,
"text": "<UNPACKED_FILES_DIR> python Makespec.py -F -p <PYTHON_LIB_PATH> <PYTHON_SCRIPT>\n -F: Produce a single file deployment.\n -p <PYTHON_LIB_PATH>: Set base path for import (like using PYTHONPATH).\n ( e.g.: C:\\Program Files\\Python24\\Lib\\ )\n <PYTHON_SCRIPT>: Path to python script.\n python Build.py <SPECFILE>\n <SPECFILE>: Path to the specfile, that have been created in step 4! \n\n The full path to <SPECFILE>:\n <UNPACKED_FILES_DIR>/<PYTHON_SCRIPT>/<PYTHON_SCRIPT>.spec\n <SPECFILE>"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
286,459
|
<p>I'm using VB .NET 2005 and Exchange Server 2003 installed
I have found some code which gives me the ability to connect in an Exchange Server and create an appointment.
The thing is that I cannot find the CDO. Appointment.
Where can I find it and make the below code to work ?
I have tried all the examples with CDO and Outlook.
I believe that the below code need to be produced in an Exchange environment and use CDOEX.DLL ?
Appreciate any help or ideas you can give me.
Thank you</p>
<p>[Sample Code]</p>
<pre><code>sURL = "http://ExchangeServername/Exchange/testuser/calendar"
Dim oCn As ADODB.Connection = New ADODB.Connection()
'oCn.Provider = "exoledb.datasource";
'I am using the below provider because I am in the client side
oCn.Provider = "MSDAIPP.DSO"
oCn.Open(sURL, "testuser", "q1w2e3r4t5", 0)
If oCn.State = 1 Then
MsgBox("Good Connection")
Else
MsgBox("Bad Connection")
Return
End If
Dim iConfg As CDO.Configuration = New CDO.Configuration()
Dim oFields As ADODB.Fields
oFields = iConfg.Fields
oFields.Item(CDO.CdoCalendar.cdoTimeZoneIDURN).Value = CDO.CdoTimeZoneId.cdoAthens
'oFields.Item(CDO.CdoConfiguration.cdoSendEmailAddress).Value = "test@test.com"
oFields.Update()
Dim oApp As CDO.Appointment = New CDO.Appointment()
oApp.Configuration = iConfg
oApp.StartTime = Convert.ToDateTime("10/11/2001 10:00:00 AM")
oApp.EndTime = Convert.ToDateTime("10/11/2001 11:00:00 AM")
oApp.Location = "My Location"
oApp.Subject = "Test: Create Meeting in VB.NET"
oApp.TextBody = "Hello..."
'' Add recurring appointment
'' Every Thursday starting today, and repeat 3 times.
'' Save to the folder
oApp.DataSource.SaveToContainer(sURL, , _
ADODB.ConnectModeEnum.adModeReadWrite, _
ADODB.RecordCreateOptionsEnum.adCreateNonCollection, _
ADODB.RecordOpenOptionsEnum.adOpenSource, _
"", "")
oCn.Close()
oApp = Nothing
oCn = Nothing
oFields = Nothing
</code></pre>
|
[
{
"answer_id": 293360,
"author": "Patrick de Kleijn",
"author_id": 33221,
"author_profile": "https://Stackoverflow.com/users/33221",
"pm_score": 0,
"selected": false,
"text": "cdoex.dll"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
286,468
|
<p>I've got a VB.NET module that reads from a resource file to display text in the correct language. Here's my problem - this code is shared between a web application and a non-web application, In the web application, I'm using System.Web.HttpContext to determine the user's preferred language, but now my Windows app won't even compile, because it says HttpContext isn't defined (I've already tried adding an imports for the full namespace - no dice).</p>
<p>I would love to use some kind of try/catch block if I can't otherwise work around it, but that doesn't change that the windows app won't compile with a reference to HttpContext in it. Without moving this chunk of code into a new file and including it only in the web application (I don't own that app, so I'd rather not deal with those implications), is there another choice I have to deal with this?</p>
<p>If it doesn't make sense, please let me know and I'll do my best to clarify.</p>
<p><strong>SOLUTION:</strong> I just added a reference to System.Web, which allowed my application to compile. I also wrapped the HttpContext reference in an "If HttpContext.Current isnot Nothing Then...End If" block, which causes it to skip over the code if it's not running as a web application, which is exactly what I was looking for.</p>
|
[
{
"answer_id": 286574,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 1,
"selected": false,
"text": "public interface IPreferredLanguage\n{\n String PeferredLanguage { get; set; }\n}\n public class WebPeferredLanguage : IPreferredLanguage\n{\n public String PeferredLanguage\n {\n get\n {\n return // retrieve the language from the http context\n }\n set\n {\n // set the preferred language in the HttpContext\n }\n } \n}\n public class WinformsPeferredLanguage : IPreferredLanguage\n{\n public String PeferredLanguage\n {\n get; set; // automatic properties\n } \n}\n public String GetEmailMessage()\n{\n var currentLanguage = IoC.Resolve<IPreferredLanguage>().PeferredLanguage;\n return Resources[currentLanguage ].EmailMessage;\n}\n"
},
{
"answer_id": 407931,
"author": "regex",
"author_id": 23869,
"author_profile": "https://Stackoverflow.com/users/23869",
"pm_score": 3,
"selected": true,
"text": "\nif (HttpContext.Current == null)\n \nIf HttpContext.Current Is Nothing Then\n"
},
{
"answer_id": 22125496,
"author": "Tomas Kubes",
"author_id": 518530,
"author_profile": "https://Stackoverflow.com/users/518530",
"pm_score": 0,
"selected": false,
"text": "Thread.CurrentUICulture\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8114/"
] |
286,475
|
<p>It looks like the run-time compiler doesn't support the same language as the command-line compiler so if you want to use lambda expressions, extensions methods or LINQ, well, you're stuck.</p>
<p>There's more detail here:</p>
<p><a href="http://metadatalabs.com/blog/" rel="nofollow noreferrer">http://metadatalabs.com/blog/</a></p>
<p>Is this correct or is there a work-around? (Short of spawning the command-line compiler, of course.)</p>
|
[
{
"answer_id": 286509,
"author": "Jamie Penney",
"author_id": 68230,
"author_profile": "https://Stackoverflow.com/users/68230",
"pm_score": 2,
"selected": false,
"text": "CodeDomProvider provider = new CSharpCodeProvider(new Dictionary<string, string> { { \"CompilerVersion\", \"v3.5\" } });\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37263/"
] |
286,481
|
<p>I was always wondering why such a simple and basic operation like swapping the contents of two variables is not built-in for many languages.</p>
<p>It is one of the most basic programming exercises in computer science classes; it is heavily used in many algorithms (e.g. sorting); every now and then one needs it and one must use a temporary variable or use a template/generic function.</p>
<p>It is even a basic machine instruction on many processors, so that the standard scheme with a temporary variable will get optimized.</p>
<p>Many less obvious operators have been created, like the assignment operators (e.g. +=, which was probably created for reflecting the cumulative machine instructions, e.g. add ax,bx), or the ?? operator in C#.</p>
<p>So, what is the reason? Or does it actually exist, and I always missed it?</p>
|
[
{
"answer_id": 286560,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": false,
"text": "#include <algorithm>\n#include <cassert>\n\nint\nmain()\n{\n using std::swap;\n int a(3), b(5);\n swap(a, b);\n assert(a == 5 && b == 3);\n}\n swap"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26070/"
] |
286,486
|
<p>In relation to <a href="https://stackoverflow.com/questions/283431/why-would-an-command-not-recognized-error-occur-only-when-a-window-is-populated">another question</a>, how do you account for paths that may change? For example, if a program is calling a file in the same directory as the program, you can simply use the path ".\foo.py" in *nix. However, apparently Windows likes to have the path hard-coded, e.g. "C:\Python_project\foo.py".</p>
<p>What happens if the path changes? For example, the file may not be on the C: drive but on a thumb drive or external drive that can change the drive letter. The file may still be in the same directory as the program but it won't match the drive letter in the code.</p>
<p>I want the program to be cross-platform, but I expect I may have to use <strong>os.name</strong> or something to determine which path code block to use.</p>
|
[
{
"answer_id": 286499,
"author": "TheObserver",
"author_id": 20879,
"author_profile": "https://Stackoverflow.com/users/20879",
"pm_score": 0,
"selected": false,
"text": "def _isInProductionMode():\n \"\"\" returns True when running the exe, \n False when running from a script, ie development mode.\n \"\"\"\n return (hasattr(sys, \"frozen\") or # new py2exe\n hasattr(sys, \"importers\") # old py2exe\n or imp.is_frozen(\"__main__\")) #tools/freeze\n\ndef _getAppDir():\n \"\"\" returns the directory name of the script or the directory \n name of the exe\n \"\"\"\n if _isInProductionMode():\n return os.path.dirname(sys.executable)\n return os.path.dirname(__file__)\n"
},
{
"answer_id": 286801,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "PYTHONPATH . c:\\ SET PYTHONPATH=C:\\path\\to\\library\npython myapp.py\n export PYTHONPATH=./relative/path\npython myapp.py\n"
},
{
"answer_id": 286802,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 4,
"selected": true,
"text": "os.path __file__ sys.executable os.path.join('path1', 'path2') os.path.expanduser('a_path') a_path os.path.abspath('a_path') os.path.dirname('a_path') # script1.py\n# Get the path to the script2.py in the same directory\nimport os\nthis_script_path = os.path.abspath(__file__)\nthis_dir_path = os.path.dirname(this_script_path)\nscript2_path = os.path.join(this_dir_path, 'script2.py')\nprint script2_path\n ali@work:~/tmp$ python script1.py \n/home/ali/tmp/script2.py\n subprocess.Popen"
},
{
"answer_id": 286914,
"author": "crystalattice",
"author_id": 18676,
"author_profile": "https://Stackoverflow.com/users/18676",
"pm_score": -1,
"selected": false,
"text": "def openNewRecord(self, event): # wxGlade: CharSheet.<event_handler>\n \"\"\"Create a new, blank record sheet.\"\"\"\n path = os.getcwd()\n subprocess.Popen(os.path.join(path, \"TW2K_char_rec_sheet.py\"), shell=True).stdout\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18676/"
] |
286,493
|
<p>I use db2 v.9.1 on windows 2003 server so it can not use LPAD or RPAD functions scalar.
because that functions support only z/OS right?</p>
<p>Now, I use this way for pad zero when COLUMN1 type is VARCHAR</p>
<pre><code> RIGHT('0000' || COLUMN1 ,4) AS RPAD
LEFT('0000' || COLUMN1 ,4) AS LPAD
</code></pre>
<p>Have better way for replace LPAD or RPAD function?</p>
|
[
{
"answer_id": 61216244,
"author": "JOHN HOUZOURIS",
"author_id": 13315027,
"author_profile": "https://Stackoverflow.com/users/13315027",
"pm_score": 0,
"selected": false,
"text": "REPEAT('0',4) || column_name\n RIGHT varchar(10) RIGHT(REPEAT('0',4) || column_name, 10)"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24550/"
] |
286,496
|
<p>I am developing an iOS application, and trying to zip the file I have created in the application, is there any built in function able to do this?</p>
|
[
{
"answer_id": 8969690,
"author": "nlg",
"author_id": 973043,
"author_profile": "https://Stackoverflow.com/users/973043",
"pm_score": 2,
"selected": false,
"text": "-(IBAction)Zip{\nself.fileManager = [NSFileManager defaultManager];\nNSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory , NSUserDomainMask, YES);\n\nNSString *ZipLibrary = [paths objectAtIndex:0];\n\n\nNSString *fullPathToFile = [ZipLibrary stringByAppendingPathComponent:@\"backUp.zip\"];\n\n//[self.fileManager createDirectoryAtPath:fullPathToFile attributes:nil];\n\n//self.documentsDir = [paths objectAtIndex:0];\n\n\nZipFile *zipFile = [[ZipFile alloc]initWithFileName:fullPathToFile mode:ZipFileModeCreate];\n\nNSError *error = nil;\nself.fileManager = [NSFileManager defaultManager];\nNSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);\n\nself.documentsDir = [paths1 objectAtIndex:0];\nNSArray *files = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:self.documentsDir error:&error];\n//for(NSString *filename in files){\n for(int i = 0;i<files.count;i++){\n\n id myArrayElement = [files objectAtIndex:i];\n\n\n if([myArrayElement rangeOfString:@\".png\" ].location !=NSNotFound){\n NSLog(@\"add %@\", myArrayElement);\n\n\n NSString *path = [self.documentsDir stringByAppendingPathComponent:myArrayElement];\n NSDictionary *attributes = [[NSFileManager defaultManager]attributesOfItemAtPath:path error:&error];\n NSDate *Date = [attributes objectForKey:NSFileCreationDate];\n\n ZipWriteStream *streem = [zipFile writeFileInZipWithName:myArrayElement fileDate:Date compressionLevel:ZipCompressionLevelBest];\n NSData *data = [NSData dataWithContentsOfFile:path];\n // NSLog(@\"%d\",data);\n [streem writeData:data];\n [streem finishedWriting];\n }else if([myArrayElement rangeOfString:@\".txt\" ].location !=NSNotFound)\n {\n\n NSString *path = [self.documentsDir stringByAppendingPathComponent:myArrayElement];\n NSDictionary *attributes = [[NSFileManager defaultManager]attributesOfItemAtPath:path error:&error];\n NSDate *Date = [attributes objectForKey:NSFileCreationDate];\n\n ZipWriteStream *streem = [zipFile writeFileInZipWithName:myArrayElement fileDate:Date compressionLevel:ZipCompressionLevelBest];\n NSData *data = [NSData dataWithContentsOfFile:path];\n // NSLog(@\"%d\",data);\n [streem writeData:data];\n [streem finishedWriting];\n }\n}\n\n[self testcsv];\n[zipFile close];\n\n}\n"
},
{
"answer_id": 13710748,
"author": "Klaas",
"author_id": 292145,
"author_profile": "https://Stackoverflow.com/users/292145",
"pm_score": 4,
"selected": false,
"text": "ZipFile *zipFile= [[ZipFile alloc] initWithFileName:@\"test.zip\" mode:ZipFileModeCreate];\n ZipWriteStream *stream= [zipFile writeFileInZipWithName:@\"abc.txt\" compressionLevel:ZipCompressionLevelBest];\n\n[stream writeData:abcData];\n[stream finishedWriting];\n ZipFile *unzipFile= [[ZipFile alloc] initWithFileName:@\"test.zip\" mode:ZipFileModeUnzip];\n\n[unzipFile goToFirstFileInZip];\n\nZipReadStream *read= [unzipFile readCurrentFileInZip];\nNSMutableData *data= [[NSMutableData alloc] initWithLength:256];\nint bytesRead= [read readDataWithBuffer:data];\n\n[read finishedReading];\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35405/"
] |
286,508
|
<p>I've looked at the ReaderWriterLock in .NET 2.0 and the ReaderWriterLockSlim in .NET 3.5, and the slim version doesn't use kernel objects for the locking. For my context, which can potentially generate a large (but not huge) amount of objects, this sounds better.</p>
<p>But the code I write needs to be used in both .NET 2.0 and 3.5 during a transition period, so the 3.5 version, while looking good for my purposes, can't be used.</p>
<p>Does anyone have, or know of, a similar class that I can plug into .NET 2.0 and get some of the same benefits with?</p>
|
[
{
"answer_id": 286520,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "ReaderWriterLockSlim ReaderWriterLockSlim ReaderWriterLock ReaderWriterLockSlim"
},
{
"answer_id": 720653,
"author": "Dmitri Nesteruk",
"author_id": 9476,
"author_profile": "https://Stackoverflow.com/users/9476",
"pm_score": 0,
"selected": false,
"text": "ReaderWriterGate"
},
{
"answer_id": 5630473,
"author": "Dmitrii Lobanov",
"author_id": 100110,
"author_profile": "https://Stackoverflow.com/users/100110",
"pm_score": 0,
"selected": false,
"text": "ReaderWriterLock ReaderWriterLock"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
] |
286,533
|
<p>I'm testing how the classes FileStream and StreamReader work togheter. Via a Console application.
I'm trying to go in a file and read the lines and print them on the console.</p>
<p>I've been able to do it with a while-loop, but I want to try it with a foreach loop.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace testing
{
public class Program
{
public static void Main(string[] args)
{
string file = @"C:\Temp\New Folder\New Text Document.txt";
using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
using(StreamReader sr = new StreamReader(fs))
{
foreach(string line in file)
{
Console.WriteLine(line);
}
}
}
}
}
}
</code></pre>
<p>The error I keep getting for this is: Cannot convert type 'char' to 'string'</p>
<p>The while loop, which does work, looks like this:</p>
<pre><code>while((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
</code></pre>
<p>I'm probably overlooking something really basic, but I can't see it.</p>
|
[
{
"answer_id": 286539,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 2,
"selected": false,
"text": "foreach(string line in file)\n{\n Console.WriteLine(line);\n}\n"
},
{
"answer_id": 286541,
"author": "Mikael Söderström",
"author_id": 36944,
"author_profile": "https://Stackoverflow.com/users/36944",
"pm_score": 0,
"selected": false,
"text": "foreach(string line in file)\n"
},
{
"answer_id": 286551,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 1,
"selected": false,
"text": "StreamReader String file File.ReadAllLines string[] lines = File.ReadAllLines(file);\nforeach(string line in lines)\n Console.WriteLine(line);\n"
},
{
"answer_id": 286552,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 0,
"selected": false,
"text": "foreach (string line in File.ReadAllLines(file))\n{\n ..\n}\n"
},
{
"answer_id": 286553,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": false,
"text": " public static IEnumerable<string> ReadLines(string path)\n {\n using (StreamReader reader = File.OpenText(path))\n {\n string line;\n while ((line = reader.ReadLine()) != null)\n {\n yield return line;\n }\n }\n }\n File.ReadAllLines() foreach Dispose() foreach(string line in ReadLines(file))\n{\n Console.WriteLine(line);\n}\n DateTime minDate = new DateTime(2000,1,1);\n var query = from line in ReadLines(file)\n let tokens = line.Split('\\t')\n let person = new\n {\n Forname = tokens[0],\n Surname = tokens[1],\n DoB = DateTime.Parse(tokens[2])\n }\n where person.DoB >= minDate\n select person;\n foreach (var person in query)\n {\n Console.WriteLine(\"{0}, {1}: born {2}\",\n person.Surname, person.Forname, person.DoB);\n }\n"
},
{
"answer_id": 286554,
"author": "RichS",
"author_id": 6247,
"author_profile": "https://Stackoverflow.com/users/6247",
"pm_score": 0,
"selected": false,
"text": "using ( FileStream fileStream = new FileStream( file, FileMode.Open, FileAccess.Read ) )\n{\n using ( StreamReader streamReader = new StreamReader( fileStream ) )\n {\n string line = \"\";\n while ( null != ( line = streamReader.ReadLine() ) )\n {\n Console.WriteLine( line );\n }\n }\n}\n"
},
{
"answer_id": 286556,
"author": "Aleksandar",
"author_id": 29511,
"author_profile": "https://Stackoverflow.com/users/29511",
"pm_score": 6,
"selected": true,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.IO;\n\nnamespace testing\n{\n public class Program\n {\n public static void Main(string[] args)\n {\n string file = @\"C:\\Temp\\New Folder\\New Text Document.txt\";\n using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))\n { \n using(StreamReader sr = new StreamReader(fs))\n {\n while(!sr.EndOfStream)\n {\n Console.WriteLine(sr.ReadLine());\n }\n }\n }\n }\n }\n}\n"
},
{
"answer_id": 286598,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": false,
"text": "LineReader IDisposable Func<Stream> Func<TextReader> foreach var errors = from file in Directory.GetFiles(logDirectory, \"*.log\")\n from line in new LineReader(file)\n select new LogEntry(line) into entry\n where entry.Severity == Severity.Error\n select entry;\n using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nnamespace MiscUtil.IO\n{\n /// <summary>\n /// Reads a data source line by line. The source can be a file, a stream,\n /// or a text reader. In any case, the source is only opened when the\n /// enumerator is fetched, and is closed when the iterator is disposed.\n /// </summary>\n public sealed class LineReader : IEnumerable<string>\n {\n /// <summary>\n /// Means of creating a TextReader to read from.\n /// </summary>\n readonly Func<TextReader> dataSource;\n\n /// <summary>\n /// Creates a LineReader from a stream source. The delegate is only\n /// called when the enumerator is fetched. UTF-8 is used to decode\n /// the stream into text.\n /// </summary>\n /// <param name=\"streamSource\">Data source</param>\n public LineReader(Func<Stream> streamSource)\n : this(streamSource, Encoding.UTF8)\n {\n }\n\n /// <summary>\n /// Creates a LineReader from a stream source. The delegate is only\n /// called when the enumerator is fetched.\n /// </summary>\n /// <param name=\"streamSource\">Data source</param>\n /// <param name=\"encoding\">Encoding to use to decode the stream\n /// into text</param>\n public LineReader(Func<Stream> streamSource, Encoding encoding)\n : this(() => new StreamReader(streamSource(), encoding))\n {\n }\n\n /// <summary>\n /// Creates a LineReader from a filename. The file is only opened\n /// (or even checked for existence) when the enumerator is fetched.\n /// UTF8 is used to decode the file into text.\n /// </summary>\n /// <param name=\"filename\">File to read from</param>\n public LineReader(string filename)\n : this(filename, Encoding.UTF8)\n {\n }\n\n /// <summary>\n /// Creates a LineReader from a filename. The file is only opened\n /// (or even checked for existence) when the enumerator is fetched.\n /// </summary>\n /// <param name=\"filename\">File to read from</param>\n /// <param name=\"encoding\">Encoding to use to decode the file\n /// into text</param>\n public LineReader(string filename, Encoding encoding)\n : this(() => new StreamReader(filename, encoding))\n {\n }\n\n /// <summary>\n /// Creates a LineReader from a TextReader source. The delegate\n /// is only called when the enumerator is fetched\n /// </summary>\n /// <param name=\"dataSource\">Data source</param>\n public LineReader(Func<TextReader> dataSource)\n {\n this.dataSource = dataSource;\n }\n\n /// <summary>\n /// Enumerates the data source line by line.\n /// </summary>\n public IEnumerator<string> GetEnumerator()\n {\n using (TextReader reader = dataSource())\n {\n string line;\n while ((line = reader.ReadLine()) != null)\n {\n yield return line;\n }\n }\n }\n\n /// <summary>\n /// Enumerates the data source line by line.\n /// </summary>\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n }\n}\n"
},
{
"answer_id": 4373533,
"author": "Bob",
"author_id": 533193,
"author_profile": "https://Stackoverflow.com/users/533193",
"pm_score": 2,
"selected": false,
"text": "using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))\n{\n using (var streamReader = new StreamReader(fileStream))\n {\n while (!streamReader.EndOfStream)\n {\n yield return reader.ReadLine();\n }\n }\n}\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11795/"
] |
286,534
|
<p>I want to enumerate all available drive letters (which aren't already taken) in Windows using VC++.</p>
<p>How can I do this?</p>
|
[
{
"answer_id": 286550,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 3,
"selected": false,
"text": "GetLogicalDriveStrings GetVolumeInformation"
},
{
"answer_id": 286555,
"author": "JTeagle",
"author_id": 162171,
"author_profile": "https://Stackoverflow.com/users/162171",
"pm_score": 5,
"selected": true,
"text": "\":\\\" \":\\\\\" _T(\":\\\\\") DRIVE_UNKNOWN DRIVE_NO_ROOT_DIR"
},
{
"answer_id": 13661694,
"author": "Zero Infinity",
"author_id": 1028140,
"author_profile": "https://Stackoverflow.com/users/1028140",
"pm_score": 2,
"selected": false,
"text": "#include <windows.h>\n#include <cstring>\n#include <sstream>\n#include <iostream>\n\nusing namespace std;\n\nint __stdcall WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, INT nShowCmd)\n{\n HANDLE hDevice = NULL;\n HANDLE fileFind = NULL;\n while(true)\n {\n Sleep(3005);\n char drv='A';\n while(drv!='[')\n {\n Sleep(105);\n const char *charDrvCF;\n const char *charDrv;\n stringstream Str;\n string drvStr;\n Str<<drv;\n Str>>drvStr;\n string drvSpc=drvStr+\":\\\\\";\n string fCheck=\"\\\\\\\\.\\\\\";\n string fhCheck=fCheck+drvStr+\":\";\n charDrvCF=fhCheck.c_str();\n charDrv=drvSpc.c_str(); \n hDevice=CreateFile(charDrvCF,\n GENERIC_READ|GENERIC_WRITE,\n FILE_SHARE_READ|FILE_SHARE_WRITE,\n NULL,\n OPEN_EXISTING,\n 0,\n NULL);\n if(hDevice!=INVALID_HANDLE_VALUE)\n {\n switch(GetDriveType(charDrv))\n {\n case DRIVE_FIXED:\n {\n cout<<\"Fixed drive detected: \"<<charDrv<<endl;\n break;\n }\n case DRIVE_REMOVABLE:\n {\n cout<<\"Removable drive detected: \"<<charDrv<<endl;\n break;\n }\n case DRIVE_NO_ROOT_DIR:\n {\n cout<<\"There is no volume mounted at the specified path. \"<<charDrv<<endl;\n break;\n }\n case DRIVE_REMOTE:\n {\n cout<<\"The drive is a remote (network) drive. \"<<charDrv<<endl;\n break;\n }\n case DRIVE_CDROM:\n {\n cout<<\"The drive is a CD-ROM drive. \"<<charDrv<<endl;\n break;\n }\n case DRIVE_RAMDISK:\n {\n cout<<\"The drive is a RAM disk. \"<<charDrv<<endl;\n break;\n }\n case DRIVE_UNKNOWN:\n {\n cout<<\"The drive type cannot be determined. \"<<charDrv<<endl;\n break;\n }\n }\n }\n drv++;\n }\n }\n}\n"
},
{
"answer_id": 57748722,
"author": "user_number153",
"author_id": 11639160,
"author_profile": "https://Stackoverflow.com/users/11639160",
"pm_score": 2,
"selected": false,
"text": "std::vector<std::string> getListOfDrives() {\n std::vector<std::string> arrayOfDrives;\n char* szDrives = new char[MAX_PATH]();\n if (GetLogicalDriveStringsA(MAX_PATH, szDrives));\n for (int i = 0; i < 100; i += 4)\n if (szDrives[i] != (char)0) \n arrayOfDrives.push_back(std::string{szDrives[i],szDrives[i+1],szDrives[i+2]});\n delete[] szDrives;\n return arrayOfDrives;\n}\n std::vector<std::string> drives = getListOfDrives();\n\nfor (std::string currentDrive : drives) {\n std::cout << currentDrive << std::endl;\n}\n"
},
{
"answer_id": 63510433,
"author": "Michael Haephrati",
"author_id": 1592639,
"author_profile": "https://Stackoverflow.com/users/1592639",
"pm_score": 0,
"selected": false,
"text": "for (w_chDrv = 'C'; w_chDrv <= 'Z'; w_chDrv++)\n{\n // make root path\n _stprintf_s(w_szRootPath, 3, _T(\"%c:\"), w_chDrv);\n\n // get driver type\n w_nDriverType = GetDriveType(w_szRootPath);\n if ((w_nDriverType != DRIVE_REMOVABLE) && (w_nDriverType != DRIVE_FIXED))\n continue;\n // if you got here that means w_szRootPath is a valid drive\n}\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7891/"
] |
286,543
|
<p>I have a checkbox in GridViewColumn which i use for show/change database value. The click event for the checkbox is used for change value in the database. For handling the state of property "IsChecked" I'm using datatrigger and a setter, se xaml code below:</p>
<pre><code><Style TargetType="CheckBox">
<Setter Property="IsEnabled" Value="True" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=ID, Converter={StaticResource Converter}}" Value="true">
<Setter Property="IsChecked" Value="True"/>
</DataTrigger>
</Style.Triggers>
</Style>
</code></pre>
<p>The binding works great until I click the checkbox. After I clicked the checkbox for the first time the state of the property "IsChecked" don't updates if a manually in the Database change the value which i mapped to the property "IsChecked".
If I map for example the same value to the property "Content" of the checkbox the trigger works fine even after I've clicked the checkbox. </p>
<p>Does anyone no whats the problem is?</p>
|
[
{
"answer_id": 286918,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 3,
"selected": true,
"text": "<Style TargetType=\"CheckBox\">\n <Style TargetType=\"{x:Type CheckBox}\">\n <Style TargetType=\"{x:Type CheckBox}\" >\n <Setter Property=\"IsChecked\" Value=\"{Binding Path=ID, Converter={StaticResource Converter}}\" />\n </Style>\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37271/"
] |
286,549
|
<p>Can PL/SQL procedure in Oracle know it's own name?</p>
<p>Let me explain:</p>
<pre><code>CREATE OR REPLACE procedure some_procedure is
v_procedure_name varchar2(32);
begin
v_procedure_name := %%something%%;
end;
</code></pre>
<p>After <code>%%something%%</code> executes, variable <code>v_procedure_name</code> should contain 'SOME_PROCEDURE'. It is also OK if it contains <code>object_id</code> of that procedure, so I can look up name in <code>all_objects</code>.</p>
|
[
{
"answer_id": 286569,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 6,
"selected": true,
"text": "v_procedure_name := $$PLSQL_UNIT;\n"
},
{
"answer_id": 18705074,
"author": "T. L. Jones",
"author_id": 2762494,
"author_profile": "https://Stackoverflow.com/users/2762494",
"pm_score": 2,
"selected": false,
"text": "EXCEPTION CREATE OR REPLACE procedure some_procedure is\n v_procedure_name varchar2(32);\nbegin\n v_procedure_name := owa_util.get_procedure;\nend;\n\nCREATE OR REPLACE PACKAGE some_package\nAS\n FUNCTION v_function_name\n RETURN DATE;\nEND;\n/\nCREATE OR REPLACE PACKAGE BODY some_package\nAS\n FUNCTION v_function_name\n RETURN DATE\n IS\n BEGIN\n RETURN SYSDATE;\n EXCEPTION\n WHEN OTHERS THEN\n DBMS_OUTPUT.PUT_LINE('ERROR IN '||owa_util.get_procedure);\n DBMS_OUTPUT.PUT_LINE(SQLERRM);\n END;\nEND;\n/\n"
},
{
"answer_id": 51368272,
"author": "Howard Shulman",
"author_id": 10089985,
"author_profile": "https://Stackoverflow.com/users/10089985",
"pm_score": 0,
"selected": false,
"text": "FUNCTION SET_PROC RETURN VARCHAR2 IS\nBEGIN\n RETURN NVL(REGEXP_SUBSTR(DBMS_UTILITY.FORMAT_CALL_STACK, \n 'procedure.+\\.(.+)\\s', 1,1,'i',1), 'UNDEFINED');\nEND SET_PROC;\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23220/"
] |
286,564
|
<p>Does Ruby have any tools along the lines of <a href="http://pypi.python.org/pypi/pylint" rel="noreferrer">pylint</a> for analyzing source code for errors and simple coding standards?</p>
<p>It would be nice if it could be integrated with <a href="http://cruisecontrolrb.thoughtworks.com/" rel="noreferrer">cruisecontrolrb</a> for continuous integration.</p>
<p>Or does everyone write such good tests that they don't need source code checkers!</p>
|
[
{
"answer_id": 310940,
"author": "Atiaxi",
"author_id": 2555346,
"author_profile": "https://Stackoverflow.com/users/2555346",
"pm_score": 2,
"selected": false,
"text": "ruby -w\n"
},
{
"answer_id": 892656,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "gem sources -a http://gems.github.com\nsudo gem install simplabs-excellent\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2761/"
] |
286,565
|
<p>I'm using a QTableWidget to display several rows. Some of these rows should reflect an error and their text color is changed :</p>
<p>Rows reflecting that there is no error are displayed with a default color (black text on white background on my computer).<br>
Rows reflecting that there is an error are displayed with a red text color (which is red text on white background on my computer).</p>
<p>This is all fine as long as there is no selection. As soon as a row is selected, no matter of the unselected text color, the text color becomes always white (on my computer) over a blue background.</p>
<p>This is something I would like to change to get the following :<br>
When a row is selected, if the row is reflecting there is no error, I would like it to be displayed with white text on blue background (default behavior).<br>
If the row is reflecting an error and is selected, I would like it to be displayed with red text on blue background.</p>
<p>So far I have only been able to change the selection color for the whole QTableWidget, which is not what I want !</p>
|
[
{
"answer_id": 287660,
"author": "Caleb Huitt - cjhuitt",
"author_id": 9876,
"author_profile": "https://Stackoverflow.com/users/9876",
"pm_score": 0,
"selected": false,
"text": "QAbstractItemDelegate"
},
{
"answer_id": 298160,
"author": "Jérôme",
"author_id": 2796,
"author_profile": "https://Stackoverflow.com/users/2796",
"pm_score": 4,
"selected": true,
"text": "class MyItemDelegate: public QItemDelegate\n{\npublic:\n MyItemDelegate(QObject* pParent = 0) : QItemDelegate(pParent)\n {\n }\n\n void paint(QPainter* pPainter, const QStyleOptionViewItem& rOption, const QModelIndex& rIndex) const \n {\n QStyleOptionViewItem ViewOption(rOption);\n\n QColor ItemForegroundColor = rIndex.data(Qt::ForegroundRole).value<QColor>();\n if (ItemForegroundColor.isValid())\n {\n if (ItemForegroundColor != rOption.palette.color(QPalette::WindowText))\n {\n ViewOption.palette.setColor(QPalette::HighlightedText, ItemForegroundColor);\n }\n }\n QItemDelegate::paint(pPainter, ViewOption, rIndex);\n }\n};\n QTableWidget* pTable = new QTableWidget(...);\npTable->setItemDelegate(new MyItemDelegate(this));\n"
},
{
"answer_id": 326736,
"author": "Harald Scheirich",
"author_id": 22080,
"author_profile": "https://Stackoverflow.com/users/22080",
"pm_score": 1,
"selected": false,
"text": "QStyleOption rIndex.data(ValidRole)"
},
{
"answer_id": 406653,
"author": "Henrik Hartz",
"author_id": 50830,
"author_profile": "https://Stackoverflow.com/users/50830",
"pm_score": 0,
"selected": false,
"text": " QVariant MySortFilterProxyModel::data(const QModelIndex & index, int role = Qt::DisplayRole) {\n // assuming error state and modelindex row match\n if (role==Qt::BackgroundRole)\n return Qt::red;\n }\n"
},
{
"answer_id": 1009553,
"author": "Krsna",
"author_id": 105627,
"author_profile": "https://Stackoverflow.com/users/105627",
"pm_score": 2,
"selected": false,
"text": "selectionChanged() OnTableSelectionChanged() if (noError)\n{\n pTable->setStyleSheet(\"QTableView {selection-background-color: #000000; selection-color: #FFFFFF;}\");\n}\nelse\n{\n pTable->setStyleSheet(\"QTableView {selection-background-color: #FF0000; selection-color: #0000FF;}\");\n}\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2796/"
] |
286,570
|
<p>I have several init.d scripts that I'm using to start some daemons. Most of these scripts I've found on the internet and they all use start-stop-daemon. My understanding is that "start-stop-daemon" is a command that is specific to Linux or BSD distros and is not available on Solaris.</p>
<p>What is the best way to translate my init.d scripts from Linux to Solaris? Is there a command equivalent to start-stop-daemon that I can use, roughly?</p>
<p>Since I'm not much of a Solaris user, I'm willing to admit upfront that I don't even know if my question is inherently invalid or not.</p>
|
[
{
"answer_id": 286673,
"author": "Anders Westrup",
"author_id": 36845,
"author_profile": "https://Stackoverflow.com/users/36845",
"pm_score": 4,
"selected": true,
"text": "svcs svccfg svcadm"
},
{
"answer_id": 674955,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "#!/sbin/sh\n\nstartcmd () {\n /usr/local/bin/rsync --daemon # REPLACE WITH YOUR COMMANDS\n}\n\nstopcmd () {\n pkill -f \"/usr/local/bin/rsync --daemon\" # REPLACE WITH YOUR COMMANDS\n}\n\ncase \"$1\" in\n'start')\n startcmd\n ;;\n'stop')\n stopcmd\n ;;\n'restart')\n stopcmd\n sleep 1\n startcmd\n ;;\n*)\n echo \"Usage: $0 { start | stop | restart }\"\n exit 1\n ;;\nesac\n ln rsync /etc/rc3.d/S91rsync\nfor i in `ls -1d /etc/rc*.d | grep -v 3`; do ln rsync $i/K02rsync; done\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35341/"
] |
286,571
|
<p>As the title really, I'm in one part of my code and I would like to invoke any methods that have been added to the Button.Click handler.</p>
<p>How can I do this?</p>
|
[
{
"answer_id": 286595,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 1,
"selected": false,
"text": " private EventHandler ButtonClick;\n\n protected override void CreateChildControls()\n {\n base.CreateChildControls();\n\n m_Button = new Button{Text = \"Do something\"};\n\n m_Button.Click += ButtonClick;\n\n ButtonClick += button_Click;\n\n Controls.Add(m_Button);\n\n }\n\n private void MakeButtonDoStuff()\n {\n ButtonClick.Invoke(this, new EventArgs());\n }\n\n private void button_Click(object sender, EventArgs e)\n {\n\n }\n"
},
{
"answer_id": 286665,
"author": "flesh",
"author_id": 27805,
"author_profile": "https://Stackoverflow.com/users/27805",
"pm_score": 2,
"selected": false,
"text": " Type t = typeof(Button);\n object[] p = new object[1];\n p[0] = EventArgs.Empty;\n MethodInfo m = t.GetMethod(\"OnClick\", BindingFlags.NonPublic | BindingFlags.Instance);\n m.Invoke(btnYourButton, p);\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26081/"
] |
286,583
|
<p>I want to print styled html pages with their images from a script. Can anyone suggest an open-source solution?</p>
<p>I'm using linux (Ubuntu 8.04) but would be also be interested in solutions for other operating systems.</p>
|
[
{
"answer_id": 286698,
"author": "Tader",
"author_id": 30700,
"author_profile": "https://Stackoverflow.com/users/30700",
"pm_score": 4,
"selected": true,
"text": "sudo aptitude install html2ps lpr html2ps \\\n http://stackoverflow.com/questions/286583 \\\n |lpr\n html2ps \\\n http://stackoverflow.com/questions/286583 \\\n |ps2pdf - stackoverflow.pdf\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20074/"
] |
286,584
|
<p>I need a member of my class to be a Control, and for it to implement an interface we define.</p>
<p>If I declare it like this...</p>
<pre><code>public class MyClass
{
public Control MyMember;
}
</code></pre>
<p>... then I don't get the interface methods, but if I declare it like this...</p>
<pre><code>public class MyClass
{
public IMyInterface MyMember;
}
</code></pre>
<p>...then I don't get the Control methods. Is there a way to specify that MyMember must be initialised to a type that inherits from both? I can't find one on MSDN. Something like...</p>
<pre><code>public class MyClass
{
public Control : IMyInterface MyMember;
}
</code></pre>
<p>... or ...</p>
<pre><code>public class MyClass
{
public Control MyMember : IMyInterface;
}
</code></pre>
<p>... except that neither of those work. Can I specify interfaces when I declare a member, and if so, how?</p>
|
[
{
"answer_id": 286591,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": -1,
"selected": false,
"text": "public interface IMyInterface : Control\n{\n ..\n}\n public interface IMyInterface \n{\n Control Control { get; }\n\n [..rest of the definition..]\n}\n class MyControl : Control, IMyInterface\n{\n public Control Control { get { return this; } }\n\n [..rest of the implementation..]\n}\n"
},
{
"answer_id": 286597,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 2,
"selected": false,
"text": "public interface MyClass {\n public T GetMyControl() where T : Control, IMyInterface { /* ........ */ }\n}\n"
},
{
"answer_id": 286608,
"author": "nullDev",
"author_id": 6621,
"author_profile": "https://Stackoverflow.com/users/6621",
"pm_score": 0,
"selected": false,
"text": "class MyControl : Control, IMyInterface\n{\n}\n public class MyClass\n{\n public MyControl MyMember;\n}\n"
},
{
"answer_id": 287324,
"author": "user37325",
"author_id": 37325,
"author_profile": "https://Stackoverflow.com/users/37325",
"pm_score": 1,
"selected": false,
"text": "public class MyGenericClass<T> where T : Control, IMyInterface\n{\n public T t;\n}\n public class MyClass\n{\n private IMyInterface m_field;\n public Control FieldAsControl\n {\n get { return m_field as Control; }\n }\n public IMyInterface Field\n {\n get { return m_field; }\n set\n {\n if (m_field is Control)\n {\n m_field = value;\n }\n else\n {\n throw new ArgumentException();\n }\n }\n }\n}\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
] |
286,589
|
<p>I'm writing a ruby program that executes some external command-line utilities. How could I mock the filesystem from my rspec tests so that I could easily setup some file hierarchy and verify it after testing. It would also be best to be implemented in ram so that tests would run quickly. </p>
<p>I realize that I may not find a portable solution as my external utilities are native programs interacting directly with operating system file services. Linux is my primary platform and solution for that would suffice.</p>
|
[
{
"answer_id": 286796,
"author": "Adam Byrtek",
"author_id": 36656,
"author_profile": "https://Stackoverflow.com/users/36656",
"pm_score": 4,
"selected": true,
"text": "File.exist? File.directory?"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30958/"
] |
286,594
|
<p>I normally work on single threaded applications and have generally never really bothered with dealing with threads. My understanding of how things work - which certainly, may be wrong - is that as long as we're always dealing with single threaded code (i.e. no forks or anything like that) it will always be executed in the same thread.</p>
<p>Is this assumption correct? I have a fuzzy idea that UI libraries/frameworks may spawn off threads of their own to handle GUI stuff (which accounts for the fact that the Windows task manager tells me that my 'single threaded' application is actually running on 10 threads) but I'm guessing that this shouldn't affect me?</p>
<p>How does this apply to COM? For instance, if I were to create an instance of a COM component in my code; and that COM component writes some information to a thread-based location (using <code>System.Threading.Thread.GetData</code> for instance) will my application be able to get hold of that information?</p>
<p>So in summary:</p>
<ol>
<li><p>In single threaded code, can I be sure that whatever I store in a thread-based location can be retrievable from anywhere else in the code?</p></li>
<li><p>If that single threaded code were to create an instance of a COM component which stores some information in a thread-based location, can that be similarly retrievable from anywhere else?</p></li>
</ol>
|
[
{
"answer_id": 286664,
"author": "Marco M.",
"author_id": 28375,
"author_profile": "https://Stackoverflow.com/users/28375",
"pm_score": 3,
"selected": true,
"text": "void AssertSingleThread()\n{\n if (m_ThreadId < 0) m_ThreadId = Thread.CurrentThread.ManagedThreadId;\n Debug.Assert(m_ThreadId == Thread.CurrentThread.ManagedThreadId);\n}\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4368/"
] |
286,603
|
<p>I have an application that uses <code>Ajax.Request</code> and its <code>onSuccess</code> event handler in lots of places.</p>
<p>I need to call a function (that will check the response) before all these <code>onSuccess</code> events fire. I tried using <code>Ajax.Responders.register</code> with <code>onComplete</code> event but it fires after <code>Ajax.Request</code>'s <code>onSuccess</code> event. Any suggestions?</p>
|
[
{
"answer_id": 286672,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "Ajax.Request onCreate onUninitialized onLoading onLoaded onInteractive onXYZ onSuccess onFailure onComplete onLoading onLoaded onInteractive onCreate"
},
{
"answer_id": 304636,
"author": "Thomas Hansen",
"author_id": 29746,
"author_profile": "https://Stackoverflow.com/users/29746",
"pm_score": 0,
"selected": false,
"text": "var oldFunc = Ajax.Request.onSuccess;\nAjax.Request.onSuccess = function foo() {\n alert('t');\n oldFunc.apply(this, arguments);\n}\n"
},
{
"answer_id": 846683,
"author": "Aleksander Krzywinski",
"author_id": 104348,
"author_profile": "https://Stackoverflow.com/users/104348",
"pm_score": 2,
"selected": true,
"text": "new Ajax.Request('example.html', {\n parameters: {action: 'update'},\n onSuccess: this.updateSuccessful\n});\n new Ajax.Request('example.html', {\n parameters: {action: 'update'},\n onSuccess: this.updateSuccessful.wrap(validateResponse)\n});\n // If you use the X-JSON-header of the response for JSON, add the third param\nfunction validateResponse(originalFn, transport /*, json */) {\n // Validate the transport\n\n if (someConditionMet) {\n originalFn(transport /*, json */);\n }\n}\n"
},
{
"answer_id": 2205477,
"author": "seth",
"author_id": 245232,
"author_profile": "https://Stackoverflow.com/users/245232",
"pm_score": 2,
"selected": false,
"text": "Ajax.Responders.register({\n\n onCreate: function(request) {\n\n request.options['onSuccess'] = request.options['onSuccess'].wrap(validateResponse);\n\n }\n\n});\n"
},
{
"answer_id": 3123282,
"author": "Gabi Purcaru",
"author_id": 376873,
"author_profile": "https://Stackoverflow.com/users/376873",
"pm_score": 1,
"selected": false,
"text": "\nvar tmp = Ajax.Request;\nAjax.Request = function(url, args) {\n // stuff to do before the request is sent\n var c = Object.clone(args);\n c.onSuccess = function(transport){\n // stuff to do when request is successful, before the callback\n args.onSuccess(transport);\n }\n\n var a = new tmp(url, c);\n return a;\n}\nAjax.Request.protoype = new tmp();\nAjax.Request.Events = tmp.Events;\ndelete tmp;\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25768/"
] |
286,605
|
<p>I am trying to create a Key Listener in java however when I try </p>
<pre><code>KeyListener listener = new KeyListener();
</code></pre>
<p>Netbeans is telling me that KeyListener is abstract;cannot be instantiated. I know that I am missing some other piece of this key listener, but since this is my first time using a key listener i am unsure of what else i need. Why is it telling me this?</p>
<p>Thanks,</p>
<p>Tomek</p>
|
[
{
"answer_id": 286613,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "KeyListener KeyListener listener = new SomeKeyListenerImplementation();\n KeyListener listener = new KeyListener()\n{\n public void keyPressed(KeyEvent e) { /* ... */ }\n\n public void keyReleased(KeyEvent e) { /* ... */ }\n\n public void keyTyped(KeyEvent e) { /* ... */ }\n};\n"
},
{
"answer_id": 287500,
"author": "Joey Gibson",
"author_id": 6645,
"author_profile": "https://Stackoverflow.com/users/6645",
"pm_score": 3,
"selected": false,
"text": "KeyListener listener = new KeyAdapter()\n{\n public void keyPressed(KeyEvent e) { /* ... */ }\n};\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29326/"
] |
286,606
|
<p>In the application there is a dialog where only numeric string entries are valid. Therefore I would like to set the numeric keyboard layout.</p>
<p>Does anyone know how to simulate key press on the keyboard or any other method to change the keyboard layout?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 286785,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 0,
"selected": false,
"text": "InputModeEditor.SetInputMode(textBox1,InputMode.Numeric);\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22996/"
] |
286,614
|
<p>I'm developing an application with a team in .Net (C++) and provide a COM interface to interact with python and other languages.</p>
<p>What we've found is that pushing data through COM turns out to be pretty slow.</p>
<p>I've considered several alternatives:</p>
<ul>
<li>dumping data to a file and sending the file path through com</li>
<li>Shared Memory via <a href="http://docs.python.org/library/mmap.html?highlight=shared%20memory#module-mmap" rel="nofollow noreferrer">mmap</a>?</li>
<li>Stream data through a socket directly?</li>
</ul>
<p>From your experience what's the best way to pass around data?</p>
|
[
{
"answer_id": 286738,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 4,
"selected": true,
"text": "win32pipe r'\\\\.\\pipe\\mypipe' ovpipe win32event.WaitForMultipleObjects rc = win32event.WaitForMultipleObjects(\n eventlist, # Objects to wait for.\n 0, # Wait for one object\n timeout) # timeout in milli-seconds.\n import win32event\nimport pywintypes\nimport win32file\nimport win32pipe\n\nclass ovpipe:\n\"Overlapped I/O named pipe class\"\ndef __init__(self):\n self.over=pywintypes.OVERLAPPED()\n evt=win32event.CreateEvent(None,1,0,None)\n self.over.hEvent=evt\n self.pname='mypipe'\n self.hpipe = win32pipe.CreateNamedPipe(\n r'\\\\.\\pipe\\mypipe', # pipe name \n win32pipe.PIPE_ACCESS_DUPLEX| # read/write access\n win32file.FILE_FLAG_OVERLAPPED,\n win32pipe.PIPE_TYPE_MESSAGE| # message-type pipe \n win32pipe.PIPE_WAIT, # blocking mode \n 1, # number of instances \n 512, # output buffer size \n 512, # input buffer size \n 2000, # client time-out\n None) # no security attributes\n self.buffer = win32file.AllocateReadBuffer(512)\n self.state='noconnected'\n self.chstate()\n\ndef execmsg(self):\n \"Translate the received message\"\n pass\n\ndef chstate(self):\n \"Change the state of the pipe depending on current state\"\n if self.state=='noconnected':\n win32pipe.ConnectNamedPipe(self.hpipe,self.over)\n self.state='connectwait'\n return -6\n\n elif self.state=='connectwait':\n j,self.strbuf=win32file.ReadFile(self.hpipe,self.buffer,self.over)\n self.state='readwait'\n return -6\n\n elif self.state=='readwait':\n size=win32file.GetOverlappedResult(self.hpipe,self.over,1)\n self.msg=self.strbuf[:size]\n ret=self.execmsg()\n self.state = 'noconnected'\n win32pipe.DisconnectNamedPipe(self.hpipe)\n return ret\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24718/"
] |
286,619
|
<p>I am using a .Net <code>HtmlTextWriter</code> to generate HTML.</p>
<pre><code>try
{
htw.RenderBeginTag( HtmlTextWriterTag.Span );
htw.Write(myObject.GenerateHtml());
htw.RenderEndTag( );
}
catch (Exception e)
{
GenerateHtmlErrorMessage(htw);
}
</code></pre>
<p>In this example, if an error exception is fired during <code>myObject.GenerateHtml()</code>, I will generate a nice error html but it will be preceded by an opening <code>span</code> tag that is never closed.</p>
<p>I could refactor it like so</p>
<pre><code>try
{
string myHtml = myObject.GenerateHtml();
// now hope we don't get any more exceptions
htw.RenderBeginTag( HtmlTextWriterTag.Span );
htw.Write(myHtml)
htw.RenderEndTag( );
}
catch (Exception e)
{
GenerateHtmlErrorMessage(htw);
}
</code></pre>
<p>Now my span doesn't open 'till I've done the hard work, but this just looks awkward to me. Is there any way do rollback with a HtmlWriter? Even if I had to put in loads of using blocks.</p>
<p>I'm currently working in .Net 2.0, but a discussion of solutions in 3.5 would be ok.</p>
|
[
{
"answer_id": 286661,
"author": "Mikael Söderström",
"author_id": 36944,
"author_profile": "https://Stackoverflow.com/users/36944",
"pm_score": -1,
"selected": false,
"text": "if (myHTML != null)\n{\n htw.RenderBeginTag( HtmlTextWriterTag.Span );\n htw.Write(myHtml) \n htw.RenderEndTag( );\nelse\n{\n GenerateHtmlErrorMessage(htw);\n}\n"
},
{
"answer_id": 292294,
"author": "Brian B.",
"author_id": 21817,
"author_profile": "https://Stackoverflow.com/users/21817",
"pm_score": 2,
"selected": true,
"text": "htw.RenderBeginTag( HtmlTextWriterTag.Span );\ntry\n{\n htw.Write(myObject.GenerateHtml());\n}\ncatch (Exception e)\n{\n GenerateHtmlErrorMessage(htw);\n}\nfinally\n{\n htw.RenderEndTag( );\n}\n"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18107/"
] |
286,624
|
<p>I am reading log files but not all lines want to be processed straight away. I am using a queue / buffer to store the lines while they wait to be processed.</p>
<p>This queue is regularly scanned for particular lines - when they are found, they are removed from the queue (they can be anywhere in it). When there isn't a particular line to be found, lines are taken out of the start of the queue one by one to be processed.</p>
<p>Therefore, the queue needs the following:</p>
<ul>
<li>Able to be resized (or give that impression)</li>
<li>Have elements removed from anywhere</li>
<li>Have elements added (will always be at the end of the queue)</li>
<li>Be scanned quickly</li>
<li>Depending on performance, have a pointer of where it got to on the last scan.</li>
</ul>
<p>I initially wrote the code when I had little experience of Java or the API, and just used an ArrayList because I knew it would work (not necessarily because it was the best option).</p>
<p>Its performance is now becoming poor with more and more logs needing to be processed - so, what collection would you recommend to be used in this situation? There's always the possibility of writing my own too.</p>
<p>Thanks</p>
|
[
{
"answer_id": 286874,
"author": "James Camfield",
"author_id": 35033,
"author_profile": "https://Stackoverflow.com/users/35033",
"pm_score": 1,
"selected": false,
"text": "HashMap<String,LinkedList<String>>\n"
},
{
"answer_id": 287172,
"author": "Bill Michell",
"author_id": 7938,
"author_profile": "https://Stackoverflow.com/users/7938",
"pm_score": 4,
"selected": true,
"text": "equals()"
}
] |
2008/11/13
|
[
"https://Stackoverflow.com/questions/286624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35033/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.