qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
148,982
|
<p>I have a function that passes an array to another function as an argument, there will be multiple data types in this array but I want to know how to pass a function or a reference to a function so the other function can call it at any time.</p>
<p>ex.</p>
<p>function A:</p>
<pre><code>add(new Array("hello", some function));
</code></pre>
<p>function B:</p>
<pre><code>public function b(args:Array) {
var myString = args[0];
var myFunc = args[1];
}
</code></pre>
|
[
{
"answer_id": 148990,
"author": "davr",
"author_id": 14569,
"author_profile": "https://Stackoverflow.com/users/14569",
"pm_score": 3,
"selected": false,
"text": "function someFunction(foo, bar) {\n ...\n}\n\nfunction a() {\n b([\"hello\", someFunction]);\n}\n\nfunction b(args:Array) {\n var myFunc:Function = args[1];\n myFunc(123, \"helloworld\");\n}\n"
},
{
"answer_id": 164498,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "function functionToPass()\n{\n}\n\nfunction otherFunction( f:Function )\n{\n // passed-in function available here\n f();\n}\n\notherFunction( functionToPass );\n"
},
{
"answer_id": 4926184,
"author": "micsun",
"author_id": 607065,
"author_profile": "https://Stackoverflow.com/users/607065",
"pm_score": 2,
"selected": false,
"text": "add([\"string\", function():void\n{\ntrace('Code...');\n}]);\n ...\nadd([\"string\", someFunction]);\n...\n\nprivate function someFunction():void\n{\ntrace('Code...');\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
148,988
|
<p>I need to create an XML schema that validates a tree structure of an XML document. I don't know exactly the occurrences or depth level of the tree.</p>
<p>XML example:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<node>
<attribute/>
<node>
<attribute/>
<node/>
</node>
</node>
</code></pre>
<p>Which is the best way to validate it? Recursion?</p>
|
[
{
"answer_id": 149003,
"author": "Michael Brown",
"author_id": 14359,
"author_profile": "https://Stackoverflow.com/users/14359",
"pm_score": 5,
"selected": false,
"text": "<xsd:element name=\"section\">\n <xsd:complexType>\n <xsd:sequence>\n <xsd:element ref=\"title\"/>\n <xsd:element ref=\"para\" maxOccurs=\"unbounded\"/>\n <xsd:element ref=\"section\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n </xsd:sequence>\n </xsd:complexType>\n</xsd:element>\n"
},
{
"answer_id": 149010,
"author": "Dani Duran",
"author_id": 19010,
"author_profile": "https://Stackoverflow.com/users/19010",
"pm_score": 7,
"selected": true,
"text": "<xs:schema id=\"XMLSchema1\"\n targetNamespace=\"http://tempuri.org/XMLSchema1.xsd\"\n elementFormDefault=\"qualified\"\n xmlns=\"http://tempuri.org/XMLSchema1.xsd\"\n xmlns:mstns=\"http://tempuri.org/XMLSchema1.xsd\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n>\n <xs:element name=\"node\" type=\"nodeType\"></xs:element>\n\n <xs:complexType name=\"nodeType\"> \n <xs:sequence minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:element name=\"node\" type=\"nodeType\"></xs:element>\n </xs:sequence>\n </xs:complexType>\n\n</xs:schema>\n"
},
{
"answer_id": 63074091,
"author": "xperroni",
"author_id": 476920,
"author_profile": "https://Stackoverflow.com/users/476920",
"pm_score": 1,
"selected": false,
"text": "<message> <from> <to> <type> <data> <data> geometry_msgs/TwistStamped <?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n<message xmlns=\"https://stackoverflow.com/message/1.0.0\">\n <from>controller:8080</from>\n <to>drone:8080</to>\n <type>geometry_msgs/TwistStamped</type>\n <data name=\"header\">\n <data name=\"seq\">0</data>\n <data name=\"stamp\">\n <data name=\"sec\">1</data>\n <data name=\"nsec\">0</data>\n </data>\n <data name=\"frame_id\">base_link</data>\n </data>\n <data name=\"twist\">\n <data name=\"linear\">\n <data name=\"x\">1.0</data>\n <data name=\"y\">0</data>\n <data name=\"z\">1.0</data>\n </data>\n <data name=\"angular\">\n <data name=\"x\">0.3</data>\n <data name=\"y\">0</data>\n <data name=\"z\">0</data>\n </data>\n </data>\n</message>\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n<xs:schema\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n targetNamespace=\"https://stackoverflow.com/message/1.0.0\"\n elementFormDefault=\"qualified\"\n xmlns=\"https://stackoverflow.com/message/1.0.0\"\n>\n <xs:element name=\"data\">\n <xs:complexType mixed=\"true\">\n <xs:sequence>\n <xs:element ref=\"data\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\"/>\n </xs:complexType>\n </xs:element>\n\n <xs:element name=\"message\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"from\" type=\"xs:string\"/>\n <xs:element name=\"to\" type=\"xs:string\"/>\n <xs:element name=\"type\" type=\"xs:string\"/>\n <xs:element ref=\"data\" maxOccurs=\"unbounded\"/>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n</xs:schema>\n <data> <?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n<data xmlns=\"https://stackoverflow.com/message/1.0.0\" name=\"twist\">\n <data name=\"header\">\n <data name=\"seq\">0</data>\n <data name=\"stamp\">\n <data name=\"sec\">1</data>\n <data name=\"nsec\">0</data>\n </data>\n <data name=\"frame_id\">base_link</data>\n </data>\n <data name=\"twist\">\n <data name=\"linear\">\n <data name=\"x\">1.0</data>\n <data name=\"y\">0</data>\n <data name=\"z\">1.0</data>\n </data>\n <data name=\"angular\">\n <data name=\"x\">0.3</data>\n <data name=\"y\">0</data>\n <data name=\"z\">0</data>\n </data>\n </data>\n</data>\n <data> data data message <?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n<xs:schema\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n targetNamespace=\"https://stackoverflow.com/message/1.0.0\"\n elementFormDefault=\"qualified\"\n xmlns=\"https://stackoverflow.com/message/1.0.0\"\n>\n <xs:complexType name=\"data\" mixed=\"true\">\n <xs:sequence>\n <xs:element name=\"data\" type=\"data\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\"/>\n </xs:complexType>\n\n <xs:element name=\"message\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"from\" type=\"xs:string\"/>\n <xs:element name=\"to\" type=\"xs:string\"/>\n <xs:element name=\"type\" type=\"xs:string\"/>\n <xs:element name=\"data\" type=\"data\" maxOccurs=\"unbounded\"/>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n</xs:schema>\n <data> data <element>"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/148988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19012/"
] |
149,008
|
<p>I have an object that I'm testing that raises an event. What is the best way of using Rhino Mocks to check that it was raised? </p>
<p>Best I could come up with (I am certain it gets better than this):</p>
<pre><code>public void MyCallback(object sender, EventArgs e) { _flag = true;}
[Test]
public void DoSomethingRaisesEvent() {
_flag = false;
using(_mocks.Record()) {
Expect.Call(delegeate { _obj.DoSomething();});
}
using(_mocks.Playback()) {
_obj = new SomethingDoer();
_obj.SomethingWasDoneEvent += new EventHandler(MyHandler);
Assert.IsTrue(_flag);
}
}
</code></pre>
|
[
{
"answer_id": 149077,
"author": "casademora",
"author_id": 5619,
"author_profile": "https://Stackoverflow.com/users/5619",
"pm_score": 0,
"selected": false,
"text": "[Test]\npublic void MyEventTest()\n{\n\n IEventRaiser eventRaiser;\n\n mockView = _mocks.CreateMock<IView>();\n using (_mocks.Record())\n {\n mockView.DoSomethingEvent += null;\n eventRaiser = LastCall.IgnoreArguments();\n }\n using (_mocks.Playback())\n {\n new Controller(mockView, mockModel);\n eventRaiser.Raise(mockView, EventArgs.Empty);\n }\n}\n"
},
{
"answer_id": 149914,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 3,
"selected": false,
"text": "[Test]\npublic void SettingValueRaisesEvent()\n{\n bool eventRaised = false;\n Parameter param = new Parameter(\"num\", \"int\", \"1\");\n param.ValueChanged += \n delegate(object sender, ValueChangedEventArgs e)\n {\n Assert.AreEqual(\"42\", e.NewValue);\n Assert.AreEqual(\"1\", e.OldValue);\n Assert.AreEqual(\"num\", e.ParameterName);\n eventRaised = true;\n };\n param.Value = \"42\"; //should fire event.\n\n Assert.IsTrue(eventRaised, \"Event was not raised\");\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
149,024
|
<p>What does the POP3 CAPA UIDL command do?</p>
|
[
{
"answer_id": 149036,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 3,
"selected": false,
"text": "UIDL CAPA CAPA UIDL"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9587/"
] |
149,033
|
<p>I know that a float isn't appropriate to store currency values because of rounding errors. Is there a standard way to represent money in C++? </p>
<p>I've looked in the boost library and found nothing about it. In java, it seems that BigInteger is the way but I couldn't find an equivalent in C++. I could write my own money class, but prefer not to do so if there is something tested.</p>
|
[
{
"answer_id": 45910765,
"author": "Fernando",
"author_id": 3238668,
"author_profile": "https://Stackoverflow.com/users/3238668",
"pm_score": 3,
"selected": false,
"text": "#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nint main()\n{\n float bogus = 1.0 / 3.0;\n boost::multiprecision::cpp_dec_float_50 correct = 1.0 / 3.0;\n\n std::cout << std::setprecision(16) << std::fixed \n << \"float: \" << bogus << std::endl\n << \"cpp_dec_float: \" << correct << std::endl;\n \n return 0;\n}\n"
},
{
"answer_id": 69155264,
"author": "brff19",
"author_id": 8928283,
"author_profile": "https://Stackoverflow.com/users/8928283",
"pm_score": 0,
"selected": false,
"text": "long long integer C #include <stdio.h>\n\nint main()\n{\n // make BIG money from cents and dollars\n signed long long int cents = 0;\n signed long long int dollars = 0;\n\n // get the amount of cents\n printf(\"Enter the amount of cents: \");\n scanf(\"%lld\", ¢s);\n\n // get the amount of dollars\n printf(\"Enter the amount of dollars: \");\n scanf(\"%lld\", &dollars);\n\n // calculate the amount of dollars\n long long int totalDollars = dollars + (cents / 100);\n\n // calculate the amount of cents\n long long int totalCents = cents % 100;\n\n // print the amount of dollars and cents\n printf(\"The total amount is: %lld dollars and %lld cents\\n\", totalDollars, totalCents);\n}\n"
},
{
"answer_id": 73551215,
"author": "nessus_pp",
"author_id": 6358210,
"author_profile": "https://Stackoverflow.com/users/6358210",
"pm_score": 0,
"selected": false,
"text": "#include <iostream>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing namespace std;\nusing namespace boost::multiprecision;\n\nint main() {\n std::cout << std::setprecision(std::numeric_limits<cpp_dec_float_50>::max_digits10) << std::endl;\n double d1 = 1.0 / 10.0;\n cpp_dec_float_50 dec_incorrect = 1.0 / 10.0; // Incorrect! We are constructing our decimal data type from the binary representation of the double value of 1.0 / 10.0\n cpp_dec_float_50 dec_correct(cpp_dec_float_50(1.0) / 10.0);\n cpp_dec_float_50 dec_correct2(\"0.1\"); // Constructing from a decimal digit string.\n std::cout << d1 << std::endl; // 0.1000000000000000055511151231257827021181583404541015625\n std::cout << dec_incorrect << std::endl; // 0.1000000000000000055511151231257827021181583404541015625\n std::cout << dec_correct << std::endl; // 0.1\n std::cout << dec_correct2 << std::endl; // 0.1\n return 0;\n}\n double d1 cpp_dec_float_50 dec_incorrect double"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
149,037
|
<p><P>How can I instantiate a JMS queue listener in java (JRE /JDK / J2EE 1.4) that only receives messages that match a given JMSCorrelationID? The messages that I'm looking to pick up have been published to a queue and not a topic, although that can change if needed.</P>
Here's the code that I'm currently using to put the message in the queue:</p>
<pre><code>/**
* publishResponseToQueue publishes Requests to the Queue.
*
* @param jmsQueueFactory -Name of the queue-connection-factory
* @param jmsQueue -The queue name for the request
* @param response -A response object that needs to be published
*
* @throws ServiceLocatorException -An exception if a request message
* could not be published to the Topic
*/
private void publishResponseToQueue( String jmsQueueFactory,
String jmsQueue,
Response response )
throws ServiceLocatorException {
if ( logger.isInfoEnabled() ) {
logger.info( "Begin publishRequestToQueue: " +
jmsQueueFactory + "," + jmsQueue + "," + response );
}
logger.assertLog( jmsQueue != null && !jmsQueue.equals(""),
"jmsQueue cannot be null" );
logger.assertLog( jmsQueueFactory != null && !jmsQueueFactory.equals(""),
"jmsQueueFactory cannot be null" );
logger.assertLog( response != null, "Request cannot be null" );
try {
Queue queue = (Queue)_context.lookup( jmsQueue );
QueueConnectionFactory factory = (QueueConnectionFactory)
_context.lookup( jmsQueueFactory );
QueueConnection connection = factory.createQueueConnection();
connection.start();
QueueSession session = connection.createQueueSession( false,
QueueSession.AUTO_ACKNOWLEDGE );
ObjectMessage objectMessage = session.createObjectMessage();
objectMessage.setJMSCorrelationID(response.getID());
objectMessage.setObject( response );
session.createSender( queue ).send( objectMessage );
session.close();
connection.close();
} catch ( Exception e ) {
//XC3.2 Added/Modified BEGIN
logger.error( "ServiceLocator.publishResponseToQueue - Could not publish the " +
"Response to the Queue - " + e.getMessage() );
throw new ServiceLocatorException( "ServiceLocator.publishResponseToQueue " +
"- Could not publish the " +
"Response to the Queue - " + e.getMessage() );
//XC3.2 Added/Modified END
}
if ( logger.isInfoEnabled() ) {
logger.info( "End publishResponseToQueue: " +
jmsQueueFactory + "," + jmsQueue + response );
}
} // end of publishResponseToQueue method
</code></pre>
|
[
{
"answer_id": 149167,
"author": "Robin",
"author_id": 21925,
"author_profile": "https://Stackoverflow.com/users/21925",
"pm_score": 5,
"selected": true,
"text": " QueueReceiver receiver = session.createReceiver(myQueue, \"JMSCorrelationID='theid'\");\n receiver.receive()\n receiver.setListener(myListener);\n"
},
{
"answer_id": 19505822,
"author": "Trying",
"author_id": 2109070,
"author_profile": "https://Stackoverflow.com/users/2109070",
"pm_score": 0,
"selected": false,
"text": "String filter = \"JMSCorrelationID = '\" + msg.getJMSMessageID() + \"'\";\nQueueReceiver receiver = session.createReceiver(queue, filter);\n JMSCorrelationID MessageID QueueReceiver receiver = session.createReceiver(queue, \"JMSCorrelationID ='\"+id+\"'\";);\n receiver.receive(2000); receiver.setMessageListener(this);"
},
{
"answer_id": 27805185,
"author": "saptarshi",
"author_id": 1421710,
"author_profile": "https://Stackoverflow.com/users/1421710",
"pm_score": 2,
"selected": false,
"text": "package com.MQueues;\n\nimport java.util.UUID;\n\nimport javax.jms.JMSException;\nimport javax.jms.MessageProducer;\nimport javax.jms.QueueConnection;\nimport javax.jms.QueueReceiver;\nimport javax.jms.QueueSession;\nimport javax.jms.Session;\nimport javax.jms.TextMessage;\n\nimport com.sun.messaging.BasicQueue;\nimport com.sun.messaging.QueueConnectionFactory;\n\npublic class HelloProducerConsumer {\n\npublic static String queueName = \"queue0\";\npublic static String correlationId;\n\npublic static String getCorrelationId() {\n return correlationId;\n}\n\npublic static void setCorrelationId(String correlationId) {\n HelloProducerConsumer.correlationId = correlationId;\n}\n\npublic static String getQueueName() {\n return queueName;\n}\n\npublic static void sendMessage(String threadName) {\n correlationId = UUID.randomUUID().toString();\n try {\n\n // Start connection\n QueueConnectionFactory cf = new QueueConnectionFactory();\n QueueConnection connection = cf.createQueueConnection();\n QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);\n BasicQueue destination = (BasicQueue) session.createQueue(threadName);\n MessageProducer producer = session.createProducer(destination);\n connection.start();\n\n // create message to send\n TextMessage message = session.createTextMessage();\n message.setJMSCorrelationID(correlationId);\n message.setText(threadName + \"(\" + System.currentTimeMillis() \n + \") \" + correlationId +\" from Producer\");\n\n System.out.println(correlationId +\" Send from Producer\");\n producer.send(message);\n\n // close everything\n producer.close();\n session.close();\n connection.close();\n\n } catch (JMSException ex) {\n System.out.println(\"Error = \" + ex.getMessage());\n }\n}\n\npublic static void receivemessage(final String correlationId) {\n try {\n\n QueueConnectionFactory cf = new QueueConnectionFactory();\n QueueConnection connection = cf.createQueueConnection();\n QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);\n\n BasicQueue destination = (BasicQueue) session.createQueue(getQueueName());\n\n connection.start();\n\n System.out.println(\"\\n\");\n System.out.println(\"Start listen \" + getQueueName() + \" \" + correlationId +\" Queue from receivemessage\");\n long now = System.currentTimeMillis();\n\n // receive our message\n String filter = \"JMSCorrelationID = '\" + correlationId + \"'\";\n QueueReceiver receiver = session.createReceiver(destination, filter);\n TextMessage m = (TextMessage) receiver.receive();\n System.out.println(\"Received message = \" + m.getText() + \" timestamp=\" + m.getJMSTimestamp());\n\n System.out.println(\"End listen \" + getQueueName() + \" \" + correlationId +\" Queue from receivemessage\");\n\n session.close();\n connection.close();\n\n } catch (JMSException ex) {\n System.out.println(\"Error = \" + ex.getMessage());\n }\n}\n\npublic static void main(String args[]) {\n HelloProducerConsumer.sendMessage(getQueueName());\n String correlationId1 = getCorrelationId();\n HelloProducerConsumer.sendMessage(getQueueName());\n String correlationId2 = getCorrelationId();\n HelloProducerConsumer.sendMessage(getQueueName());\n String correlationId3 = getCorrelationId();\n\n\n HelloProducerConsumer.receivemessage(correlationId2);\n\n HelloProducerConsumer.receivemessage(correlationId1);\n\n HelloProducerConsumer.receivemessage(correlationId3);\n}\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231627/"
] |
149,040
|
<p>Assume the following:</p>
<p><em>models.py</em></p>
<pre><code>class Entry(models.Model):
title = models.CharField(max_length=50)
slug = models.CharField(max_length=50, unique=True)
body = models.CharField(max_length=200)
</code></pre>
<p><em>admin.py</em></p>
<pre><code>class EntryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('title',)}
</code></pre>
<p>I want the slug to be pre-populated by the title, but I dont want the user to be able to edit it from the admin. I assumed that adding the fields=[] to the admin object and not including the slug would have worked, but it didnt. I also tried setting editable=False in the model, but that also didnt work (infact, stops the page from rendering).</p>
<p>Thoughts? </p>
|
[
{
"answer_id": 149295,
"author": "Dmitry Shevchenko",
"author_id": 7437,
"author_profile": "https://Stackoverflow.com/users/7437",
"pm_score": 3,
"selected": true,
"text": "def save(self):\n from django.template.defaultfilters import slugify\n\n if not self.slug:\n self.slug = slugify(self.title)\n\n super(Your_Model_Name,self).save()\n"
},
{
"answer_id": 150296,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 0,
"selected": false,
"text": "save ModelAdmin class EntryAdmin(admin.ModelAdmin):\n exclude = ('slug',)\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22306/"
] |
149,042
|
<p>My questions is simple!</p>
<ol>
<li>Would you start learning Smalltalk if you had the time? Why? Why not?</li>
<li>Do you already know Smalltalk? Why would you recommend Smalltalk? Why not?</li>
</ol>
<p>Personally I'm a Ruby on Rails programmer and I really like it. However, I'm thinking about Smalltalk because I read various blogs and some people are calling Ruby something like "Smalltalk Light". The second reason why I'm interested in Smalltalk is <a href="http://seaside.st" rel="noreferrer">Seaside</a>.</p>
<p>Maybe someone has made the same transition before?</p>
<p><strong>EDIT:</strong> Actually, what got me most excited about Smalltalk/Seaside is the following Episode of WebDevRadio: <a href="http://www.webdevradio.com/index.php?id=77" rel="noreferrer">Episode 52: Randal Schwartz on Seaside (among other things)</a></p>
|
[
{
"answer_id": 149110,
"author": "Kevin Driedger",
"author_id": 9587,
"author_profile": "https://Stackoverflow.com/users/9587",
"pm_score": 4,
"selected": false,
"text": "i < 60\n ifTrue: [ self walk ]\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20467/"
] |
149,054
|
<p>My everyday IDE is Eclipse which has a wonderful Open Resource feature (CTRL+SHIFT+R or Navigate > Open Resource) which allows the user to search for files/resources across multiple projects.</p>
<p>I can't find a similar feature in SQL Server Management Studio, is there one?</p>
|
[
{
"answer_id": 234485,
"author": "Mark S. Rasmussen",
"author_id": 12469,
"author_profile": "https://Stackoverflow.com/users/12469",
"pm_score": 1,
"selected": false,
"text": "sp_MSforeachdb 'SELECT * FROM ?.INFORMATION_SCHEMA.routines WHERE ROUTINE_TYPE = ''PROCEDURE'''\n"
},
{
"answer_id": 57617259,
"author": "Drunken Code Monkey",
"author_id": 3440248,
"author_profile": "https://Stackoverflow.com/users/3440248",
"pm_score": 0,
"selected": false,
"text": "/*\n This script creates a CLR stored procedure and its assembly on a database that will let you search for\n keywords separated by a space on all columns of all tables of all types except 'binary', 'varbinary', 'bit',\n 'timestamp', 'image', 'sql_variant', and 'hierarchyid'. This was made as a CLR stored proc to take advantage\n of explicit parallelism to make the search a lot faster. Be aware that this will use many cores so only use\n this for occasional DBA work. This has the potential to cause a DDoS type of situation if broad searches with\n many results are hammered into the server, since each request can try to parallelize its search. An optional\n parameter exists to limit parallelism to a set number of cores. You can also set filters on the tables or\n columns to search, including logical operators OR, AND, NOT, and parenthesis (see examples below). Results\n are returned as XML rows.\n\n To install you need owner rights. Also, because SQL Server doesn't allow secondary CLR threads access to \n the stored procedure context, we extract the connection string from the first context connection we make.\n This works fine, but only if you are connected with a trusted connection (using a Windows account).\n\n ------------------------------------------------------------------\n -- CLR access must be enabled on the instance for this to work. --\n ------------------------------------------------------------------\n -- sp_configure 'show advanced options', 1; --\n -- GO --\n -- RECONFIGURE; --\n -- GO --\n -- sp_configure 'clr enabled', 1; --\n -- GO --\n -- RECONFIGURE; --\n -- GO --\n ------------------------------------------------------------------\n\n -----------------------------------------------------------------------------------\n -- Database needs to be flagged trustworthy to be able to access CLR assemblies. --\n -----------------------------------------------------------------------------------\n -- ALTER DATABASE [AdventureWorks] SET TRUSTWORTHY ON; --\n -----------------------------------------------------------------------------------\n\n Example usages:\n ---------------\n Using all available processors on the server:\n EXEC [dbo].[SearchAllTables] @valueSearchTerm = 'john michael'\n\n Limiting the server to 4 concurrent threads:\n EXEC [dbo].[SearchAllTables] @valueSearchTerm = 'john michael', @maxDegreeOfParallelism = 4\n\n Using logical operators in search terms:\n EXEC [dbo].[SearchAllTables] @valueSearchTerm = '(john or michael) and not jack', @tablesSearchTerm = 'not contact'\n\n Limiting search to table names and/or column names containing some search terms:\n EXEC [dbo].[SearchAllTables] @valueSearchTerm = 'john michael', @tablesSearchTerm = 'person contact', @columnsSearchTerm = 'address name'\n\n Limiting search results to the first row of each table where the terms are found:\n EXEC [dbo].[SearchAllTables] @valueSearchTerm = 'john michael', @getOnlyFirstRowPerTable = 1\n\n Limiting the search to the schema only automatically returns only the first row for each table:\n EXEC [dbo].[SearchAllTables] @tablesSearchTerm = 'person contact'\n\n Only return the search queries:\n EXEC [dbo].[SearchAllTables] @valueSearchTerm = 'john michael', @tablesSearchTerm = 'person contact', @onlyOutputQueries = 1\n\n Capturing results into temporary table and sorting:\n CREATE TABLE #temp (Result NVARCHAR(MAX));\n INSERT INTO #temp\n EXEC [dbo].[SearchAllTables] @valueSearchTerm = 'john';\n SELECT * FROM #temp ORDER BY Result ASC;\n DROP TABLE #temp;\n*/\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6912/"
] |
149,055
|
<p>I would like to format a price in JavaScript. I'd like a function which takes a <code>float</code> as an argument and returns a <code>string</code> formatted like this:</p>
<pre><code>"$ 2,500.00"
</code></pre>
<p>How can I do this?</p>
|
[
{
"answer_id": 149080,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 5,
"selected": false,
"text": "<script type=\"text/javascript\">\n function ins1000Sep(val) {\n val = val.split(\".\");\n val[0] = val[0].split(\"\").reverse().join(\"\");\n val[0] = val[0].replace(/(\\d{3})/g, \"$1,\");\n val[0] = val[0].split(\"\").reverse().join(\"\");\n val[0] = val[0].indexOf(\",\") == 0 ? val[0].substring(1) : val[0];\n return val.join(\".\");\n }\n\n function rem1000Sep(val) {\n return val.replace(/,/g, \"\");\n }\n\n function formatNum(val) {\n val = Math.round(val*100)/100;\n val = (\"\" + val).indexOf(\".\") > -1 ? val + \"00\" : val + \".00\";\n var dec = val.indexOf(\".\");\n return dec == val.length-3 || dec == 0 ? val : val.substring(0, dec+3);\n }\n</script>\n\n<button onclick=\"alert(ins1000Sep(formatNum(12313231)));\">\n"
},
{
"answer_id": 149099,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 11,
"selected": false,
"text": " const profits = 2489.8237;\n\n profits.toFixed(3) // Returns 2489.824 (rounds up)\n profits.toFixed(2) // Returns 2489.82\n profits.toFixed(7) // Returns 2489.8237000 (pads the decimals)\n \"$\" + profits.toFixed(2) , function formatMoney(number, decPlaces, decSep, thouSep) {\n decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,\n decSep = typeof decSep === \"undefined\" ? \".\" : decSep;\n thouSep = typeof thouSep === \"undefined\" ? \",\" : thouSep;\n var sign = number < 0 ? \"-\" : \"\";\n var i = String(parseInt(number = Math.abs(Number(number) || 0).toFixed(decPlaces)));\n var j = (j = i.length) > 3 ? j % 3 : 0;\n\n return sign +\n (j ? i.substr(0, j) + thouSep : \"\") +\n i.substr(j).replace(/(\\decSep{3})(?=\\decSep)/g, \"$1\" + thouSep) +\n (decPlaces ? decSep + Math.abs(number - i).toFixed(decPlaces).slice(2) : \"\");\n}\n\ndocument.getElementById(\"b\").addEventListener(\"click\", event => {\n document.getElementById(\"x\").innerText = \"Result was: \" + formatMoney(document.getElementById(\"d\").value);\n}); <label>Insert your amount: <input id=\"d\" type=\"text\" placeholder=\"Cash amount\" /></label>\n<br />\n<button id=\"b\">Get Output</button>\n<p id=\"x\">(press button to get output)</p> (123456789.12345).formatMoney(2, \".\", \",\");\n (123456789.12345).formatMoney(2);\n formatMoney d = d == undefined ? \",\" : d,\n t = t == undefined ? \".\" : t,\n function formatMoney(amount, decimalCount = 2, decimal = \".\", thousands = \",\") {\n try {\n decimalCount = Math.abs(decimalCount);\n decimalCount = isNaN(decimalCount) ? 2 : decimalCount;\n\n const negativeSign = amount < 0 ? \"-\" : \"\";\n\n let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString();\n let j = (i.length > 3) ? i.length % 3 : 0;\n\n return\n negativeSign +\n (j ? i.substr(0, j) + thousands : '') +\n i.substr(j).replace(/(\\d{3})(?=\\d)/g, \"$1\" + thousands) +\n (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : \"\");\n } catch (e) {\n console.log(e)\n }\n};\n\ndocument.getElementById(\"b\").addEventListener(\"click\", event => {\n document.getElementById(\"x\").innerText = \"Result was: \" + formatMoney(document.getElementById(\"d\").value);\n}); <label>Insert your amount: <input id=\"d\" type=\"text\" placeholder=\"Cash amount\" /></label>\n<br />\n<button id=\"b\">Get Output</button>\n<p id=\"x\">(press button to get output)</p>"
},
{
"answer_id": 149107,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 8,
"selected": false,
"text": "toLocaleString() toFixed() Number((someNumber).toFixed(1)).toLocaleString()\n someNumber.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});\n const money = new Intl.NumberFormat('de-CH',\n { style:'currency', currency: 'CHF' });\nconst percent = new Intl.NumberFormat('de-CH',\n { style:'percent', maximumFractionDigits: 1, signDisplay: \"always\"});\n money.format(1234.50); // output CHF 1'234.50\npercent.format(0.083); // output +8.3%\n"
},
{
"answer_id": 149120,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 4,
"selected": false,
"text": "function CurrencyFormatted(amount)\n{\n var i = parseFloat(amount);\n if(isNaN(i)) { i = 0.00; }\n var minus = '';\n if(i < 0) { minus = '-'; }\n i = Math.abs(i);\n i = parseInt((i + .005) * 100);\n i = i / 100;\n s = new String(i);\n if(s.indexOf('.') < 0) { s += '.00'; }\n if(s.indexOf('.') == (s.length - 2)) { s += '0'; }\n s = minus + s;\n return s;\n}\n"
},
{
"answer_id": 149126,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 3,
"selected": false,
"text": "format: function(nData, oConfig) {\n oConfig = oConfig || {};\n\n if(!YAHOO.lang.isNumber(nData)) {\n nData *= 1;\n }\n\n if(YAHOO.lang.isNumber(nData)) {\n var sOutput = nData + \"\";\n var sDecimalSeparator = (oConfig.decimalSeparator) ? oConfig.decimalSeparator : \".\";\n var nDotIndex;\n\n // Manage decimals\n if(YAHOO.lang.isNumber(oConfig.decimalPlaces)) {\n // Round to the correct decimal place\n var nDecimalPlaces = oConfig.decimalPlaces;\n var nDecimal = Math.pow(10, nDecimalPlaces);\n sOutput = Math.round(nData*nDecimal)/nDecimal + \"\";\n nDotIndex = sOutput.lastIndexOf(\".\");\n\n if(nDecimalPlaces > 0) {\n // Add the decimal separator\n if(nDotIndex < 0) {\n sOutput += sDecimalSeparator;\n nDotIndex = sOutput.length-1;\n }\n // Replace the \".\"\n else if(sDecimalSeparator !== \".\"){\n sOutput = sOutput.replace(\".\",sDecimalSeparator);\n }\n // Add missing zeros\n while((sOutput.length - 1 - nDotIndex) < nDecimalPlaces) {\n sOutput += \"0\";\n }\n }\n }\n\n // Add the thousands separator\n if(oConfig.thousandsSeparator) {\n var sThousandsSeparator = oConfig.thousandsSeparator;\n nDotIndex = sOutput.lastIndexOf(sDecimalSeparator);\n nDotIndex = (nDotIndex > -1) ? nDotIndex : sOutput.length;\n var sNewOutput = sOutput.substring(nDotIndex);\n var nCount = -1;\n for (var i=nDotIndex; i>0; i--) {\n nCount++;\n if ((nCount%3 === 0) && (i !== nDotIndex)) {\n sNewOutput = sThousandsSeparator + sNewOutput;\n }\n sNewOutput = sOutput.charAt(i-1) + sNewOutput;\n }\n sOutput = sNewOutput;\n }\n\n // Prepend prefix\n sOutput = (oConfig.prefix) ? oConfig.prefix + sOutput : sOutput;\n\n // Append suffix\n sOutput = (oConfig.suffix) ? sOutput + oConfig.suffix : sOutput;\n\n return sOutput;\n }\n // Still not a number. Just return it unaltered\n else {\n return nData;\n }\n}\n"
},
{
"answer_id": 149150,
"author": "Daniel Magliola",
"author_id": 3314,
"author_profile": "https://Stackoverflow.com/users/3314",
"pm_score": 6,
"selected": true,
"text": "var DecimalSeparator = Number(\"1.2\").toLocaleString().substr(1,1);\n\nvar AmountWithCommas = Amount.toLocaleString();\nvar arParts = String(AmountWithCommas).split(DecimalSeparator);\nvar intPart = arParts[0];\nvar decPart = (arParts.length > 1 ? arParts[1] : '');\ndecPart = (decPart + '00').substr(0,2);\n\nreturn '£ ' + intPart + DecimalSeparator + decPart;\n"
},
{
"answer_id": 149371,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 3,
"selected": false,
"text": "function formatMoney(n) {\n return \"$ \" + (Math.round(n * 100) / 100).toLocaleString();\n}\n function formatMoney(n) {\n return \"$ \" + n.toLocaleString().split(\".\")[0] + \".\"\n + n.toFixed(2).split(\".\")[1];\n}\n"
},
{
"answer_id": 1323064,
"author": "DaMayan",
"author_id": 162092,
"author_profile": "https://Stackoverflow.com/users/162092",
"pm_score": 5,
"selected": false,
"text": "function number_format (number, decimals, dec_point, thousands_sep) {\n var n = number, prec = decimals;\n\n var toFixedFix = function (n,prec) {\n var k = Math.pow(10,prec);\n return (Math.round(n*k)/k).toString();\n };\n\n n = !isFinite(+n) ? 0 : +n;\n prec = !isFinite(+prec) ? 0 : Math.abs(prec);\n var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;\n var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;\n\n var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec);\n // Fix for Internet Explorer parseFloat(0.55).toFixed(0) = 0;\n\n var abs = toFixedFix(Math.abs(n), prec);\n var _, i;\n\n if (abs >= 1000) {\n _ = abs.split(/\\D/);\n i = _[0].length % 3 || 3;\n\n _[0] = s.slice(0,i + (n < 0)) +\n _[0].slice(i).replace(/(\\d{3})/g, sep+'$1');\n s = _.join(dec);\n } else {\n s = s.replace('.', dec);\n }\n\n var decPos = s.indexOf(dec);\n if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {\n s += new Array(prec-(s.length-decPos-1)).join(0)+'0';\n }\n else if (prec >= 1 && decPos === -1) {\n s += dec+new Array(prec).join(0)+'0';\n }\n return s;\n}\n // Formats a number with grouped thousands\n//\n// version: 906.1806\n// discuss at: http://phpjs.org/functions/number_format\n// + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)\n// + bugfix by: Michael White (http://getsprink.com)\n// + bugfix by: Benjamin Lupton\n// + bugfix by: Allan Jensen (http://www.winternet.no)\n// + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n// + bugfix by: Howard Yeend\n// + revised by: Luke Smith (http://lucassmith.name)\n// + bugfix by: Diogo Resende\n// + bugfix by: Rival\n// + input by: Kheang Hok Chin (http://www.distantia.ca/)\n// + improved by: davook\n// + improved by: Brett Zamir (http://brett-zamir.me)\n// + input by: Jay Klehr\n// + improved by: Brett Zamir (http://brett-zamir.me)\n// + input by: Amir Habibi (http://www.residence-mixte.com/)\n// + bugfix by: Brett Zamir (http://brett-zamir.me)\n// * example 1: number_format(1234.56);\n// * returns 1: '1,235'\n// * example 2: number_format(1234.56, 2, ',', ' ');\n// * returns 2: '1 234,56'\n// * example 3: number_format(1234.5678, 2, '.', '');\n// * returns 3: '1234.57'\n// * example 4: number_format(67, 2, ',', '.');\n// * returns 4: '67,00'\n// * example 5: number_format(1000);\n// * returns 5: '1,000'\n// * example 6: number_format(67.311, 2);\n// * returns 6: '67.31'\n// * example 7: number_format(1000.55, 1);\n// * returns 7: '1,000.6'\n// * example 8: number_format(67000, 5, ',', '.');\n// * returns 8: '67.000,00000'\n// * example 9: number_format(0.9, 0);\n// * returns 9: '1'\n// * example 10: number_format('1.20', 2);\n// * returns 10: '1.20'\n// * example 11: number_format('1.20', 4);\n// * returns 11: '1.2000'\n// * example 12: number_format('1.2000', 3);\n// * returns 12: '1.200'\n"
},
{
"answer_id": 2866613,
"author": "Marco Demaio",
"author_id": 260080,
"author_profile": "https://Stackoverflow.com/users/260080",
"pm_score": 7,
"selected": false,
"text": "/*\ndecimal_sep: character used as decimal separator, it defaults to '.' when omitted\nthousands_sep: char used as thousands separator, it defaults to ',' when omitted\n*/\nNumber.prototype.toMoney = function(decimals, decimal_sep, thousands_sep)\n{\n var n = this,\n c = isNaN(decimals) ? 2 : Math.abs(decimals), // If decimal is zero we must take it. It means the user does not want to show any decimal\n d = decimal_sep || '.', // If no decimal separator is passed, we use the dot as default decimal separator (we MUST use a decimal separator)\n\n /*\n According to [https://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function]\n the fastest way to check for not defined parameter is to use typeof value === 'undefined'\n rather than doing value === undefined.\n */\n t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, // If you don't want to use a thousands separator you can pass empty string as thousands_sep value\n\n sign = (n < 0) ? '-' : '',\n\n // Extracting the absolute value of the integer part of the number and converting to string\n i = parseInt(n = Math.abs(n).toFixed(c)) + '',\n\n j = ((j = i.length) > 3) ? j % 3 : 0;\n return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\\d{3})(?=\\d)/g, \"$1\" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');\n}\n // Some tests (do not forget parenthesis when using negative numbers and number with no decimals)\nalert(123456789.67392.toMoney() + '\\n' + 123456789.67392.toMoney(3) + '\\n' + 123456789.67392.toMoney(0) + '\\n' + (123456).toMoney() + '\\n' + (123456).toMoney(0) + '\\n' + 89.67392.toMoney() + '\\n' + (89).toMoney());\n\n// Some tests (do not forget parenthesis when using negative numbers and number with no decimals)\nalert((-123456789.67392).toMoney() + '\\n' + (-123456789.67392).toMoney(-3));\n Math.abs(decimals) NaN decimal_sep typeof thousands_sep === 'undefined' (+n || 0) this Number"
},
{
"answer_id": 2919971,
"author": "Richard Parnaby-King",
"author_id": 351785,
"author_profile": "https://Stackoverflow.com/users/351785",
"pm_score": 2,
"selected": false,
"text": "function getMoney(A){\n var a = new Number(A);\n var b = a.toFixed(2); // Get 12345678.90\n a = parseInt(a); // Get 12345678\n b = (b-a).toPrecision(2); // Get 0.90\n b = parseFloat(b).toFixed(2); // In case we get 0.0, we pad it out to 0.00\n a = a.toLocaleString(); // Put in commas - Internet Explorer also puts in .00, so we'll get 12,345,678.00\n // If Internet Explorer (our number ends in .00)\n if(a < 1 && a.lastIndexOf('.00') == (a.length - 3))\n {\n a = a.substr(0, a.length-3); // Delete the .00\n }\n return a + b.substr(1); // Remove the 0 from b, then return a + b = 12,345,678.90\n}\nalert(getMoney(12345678.9));\n"
},
{
"answer_id": 3284302,
"author": "Miller Medeiros",
"author_id": 278435,
"author_profile": "https://Stackoverflow.com/users/278435",
"pm_score": 4,
"selected": false,
"text": "Number.prototype.toLocaleString Number.prototype /**\n * Converts number into currency format\n * @param {number} number Number that should be converted.\n * @param {string} [decimalSeparator] Decimal separator, defaults to '.'.\n * @param {string} [thousandsSeparator] Thousands separator, defaults to ','.\n * @param {int} [nDecimalDigits] Number of decimal digits, defaults to `2`.\n * @return {string} Formatted string (e.g. numberToCurrency(12345.67) returns '12,345.67')\n */\nfunction numberToCurrency(number, decimalSeparator, thousandsSeparator, nDecimalDigits){\n //default values\n decimalSeparator = decimalSeparator || '.';\n thousandsSeparator = thousandsSeparator || ',';\n nDecimalDigits = nDecimalDigits == null? 2 : nDecimalDigits;\n\n var fixed = number.toFixed(nDecimalDigits), //limit/add decimal digits\n parts = new RegExp('^(-?\\\\d{1,3})((?:\\\\d{3})+)(\\\\.(\\\\d{'+ nDecimalDigits +'}))?$').exec( fixed ); //separate begin [$1], middle [$2] and decimal digits [$4]\n\n if(parts){ //number >= 1000 || number <= -1000\n return parts[1] + parts[2].replace(/\\d{3}/g, thousandsSeparator + '$&') + (parts[4] ? decimalSeparator + parts[4] : '');\n }else{\n return fixed.replace('.', decimalSeparator);\n }\n}\n"
},
{
"answer_id": 5342097,
"author": "Wayne",
"author_id": 592746,
"author_profile": "https://Stackoverflow.com/users/592746",
"pm_score": 6,
"selected": false,
"text": "function formatDollar(num) {\n var p = num.toFixed(2).split(\".\");\n return \"$\" + p[0].split(\"\").reverse().reduce(function(acc, num, i, orig) {\n return num + (num != \"-\" && i && !(i % 3) ? \",\" : \"\") + acc;\n }, \"\") + \".\" + p[1];\n}\n formatDollar(45664544.23423) // \"$45,664,544.23\"\nformatDollar(45) // \"$45.00\"\nformatDollar(123) // \"$123.00\"\nformatDollar(7824) // \"$7,824.00\"\nformatDollar(1) // \"$1.00\"\nformatDollar(-1345) // \"$-1,345.00\nformatDollar(-3) // \"$-3.00\"\n"
},
{
"answer_id": 5681208,
"author": "jc00ke",
"author_id": 710404,
"author_profile": "https://Stackoverflow.com/users/710404",
"pm_score": 3,
"selected": false,
"text": "Number.prototype.toMoney = (decimals = 2, decimal_separator = \".\", thousands_separator = \",\") ->\n n = this\n c = if isNaN(decimals) then 2 else Math.abs decimals\n sign = if n < 0 then \"-\" else \"\"\n i = parseInt(n = Math.abs(n).toFixed(c)) + ''\n j = if (j = i.length) > 3 then j % 3 else 0\n x = if j then i.substr(0, j) + thousands_separator else ''\n y = i.substr(j).replace(/(\\d{3})(?=\\d)/g, \"$1\" + thousands_separator)\n z = if c then decimal_separator + Math.abs(n - i).toFixed(c).slice(2) else ''\n sign + x + y + z\n"
},
{
"answer_id": 5969458,
"author": "Daniel Fernandez",
"author_id": 749340,
"author_profile": "https://Stackoverflow.com/users/749340",
"pm_score": 2,
"selected": false,
"text": "function format_currency(v, number_of_decimals, decimal_separator, currency_sign){\n return (isNaN(v)? v : currency_sign + parseInt(v||0).toLocaleString() + decimal_separator + (v*1).toFixed(number_of_decimals).slice(-number_of_decimals));\n}\n"
},
{
"answer_id": 6715476,
"author": "Goodeq",
"author_id": 645710,
"author_profile": "https://Stackoverflow.com/users/645710",
"pm_score": 5,
"selected": false,
"text": "#,##0.00 -000.#### # ##0,00 #,###.## #'###.## #,##,#0.000 #,###0.## ##,###,##.# 0#,#00#.###0# format( \"0.0000\", 3.141592)"
},
{
"answer_id": 8313159,
"author": "Julien de Prabère",
"author_id": 1071570,
"author_profile": "https://Stackoverflow.com/users/1071570",
"pm_score": 2,
"selected": false,
"text": "Number.prototype.toMonetaryString = function() {\n var n = this.toFixed(2), m;\n //var = this.toFixed(2).replace(/\\./, ','); For comma separator\n // with a space for thousands separator\n while ((m = n.replace(/(\\d)(\\d\\d\\d)\\b/g, '$1 $2')) != n)\n n = m;\n return m;\n}\n\nString.prototype.fromMonetaryToNumber = function(s) {\n return this.replace(/[^\\d-]+/g, '')/100;\n}\n"
},
{
"answer_id": 8363954,
"author": "troy",
"author_id": 1078380,
"author_profile": "https://Stackoverflow.com/users/1078380",
"pm_score": 3,
"selected": false,
"text": "String.prototype.reverse = function() {\n return this.split('').reverse().join('');\n};\n\nNumber.prototype.toCurrency = function( round_decimal /*boolean*/ ) { \n // format decimal or round to nearest integer\n var n = this.toFixed( round_decimal ? 0 : 2 );\n\n // convert to a string, add commas every 3 digits from left to right \n // by reversing string\n return (n + '').reverse().replace( /(\\d{3})(?=\\d)/g, '$1,' ).reverse();\n};\n"
},
{
"answer_id": 8726353,
"author": "Julien de Prabère",
"author_id": 1071607,
"author_profile": "https://Stackoverflow.com/users/1071607",
"pm_score": 5,
"selected": false,
"text": " Number.prototype.toCurrencyString = function(){\n return this.toFixed(2).replace(/(\\d)(?=(\\d{3})+\\b)/g, '$1 ');\n }\n\n n = 12345678.9;\n alert(n.toCurrencyString());\n"
},
{
"answer_id": 9318723,
"author": "crush",
"author_id": 1195273,
"author_profile": "https://Stackoverflow.com/users/1195273",
"pm_score": 6,
"selected": false,
"text": "f.nettotal.value = \"$\" + showValue.toFixed(2);\n"
},
{
"answer_id": 9318724,
"author": "Jonathan M",
"author_id": 751484,
"author_profile": "https://Stackoverflow.com/users/751484",
"pm_score": 7,
"selected": false,
"text": "Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator) {\n var n = this,\n decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,\n decSeparator = decSeparator == undefined ? \".\" : decSeparator,\n thouSeparator = thouSeparator == undefined ? \",\" : thouSeparator,\n sign = n < 0 ? \"-\" : \"\",\n i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + \"\",\n j = (j = i.length) > 3 ? j % 3 : 0;\n return sign + (j ? i.substr(0, j) + thouSeparator : \"\") + i.substr(j).replace(/(\\d{3})(?=\\d)/g, \"$1\" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : \"\");\n};\n $ var myMoney = 3543.75873;\nvar formattedMoney = '$' + myMoney.formatMoney(2, ',', '.'); // \"$3,543.76\"\n"
},
{
"answer_id": 9327950,
"author": "Gate",
"author_id": 656293,
"author_profile": "https://Stackoverflow.com/users/656293",
"pm_score": 4,
"selected": false,
"text": "var num = new Number(349);\ndocument.write(\"$\" + num.toFixed(2));\n"
},
{
"answer_id": 10168573,
"author": "Tim Saylor",
"author_id": 155987,
"author_profile": "https://Stackoverflow.com/users/155987",
"pm_score": 4,
"selected": false,
"text": "// Format numbers to two decimals with commas\nfunction formatDollar(num) {\n var p = num.toFixed(2).split(\".\");\n var chars = p[0].split(\"\").reverse();\n var newstr = '';\n var count = 0;\n for (x in chars) {\n count++;\n if(count%3 == 1 && count != 1) {\n newstr = chars[x] + ',' + newstr;\n } else {\n newstr = chars[x] + newstr;\n }\n }\n return newstr + \".\" + p[1];\n}\n"
},
{
"answer_id": 11264443,
"author": "Ebubekir Dirican",
"author_id": 869571,
"author_profile": "https://Stackoverflow.com/users/869571",
"pm_score": 2,
"selected": false,
"text": "String.prototype.toPrice = function () {\n var v;\n if (/^\\d+(,\\d+)$/.test(this))\n v = this.replace(/,/, '.');\n else if (/^\\d+((,\\d{3})*(\\.\\d+)?)?$/.test(this))\n v = this.replace(/,/g, \"\");\n else if (/^\\d+((.\\d{3})*(,\\d+)?)?$/.test(this))\n v = this.replace(/\\./g, \"\").replace(/,/, \".\");\n var x = parseFloat(v).toFixed(2).toString().split(\".\"),\n x1 = x[0],\n x2 = ((x.length == 2) ? \".\" + x[1] : \".00\"),\n exp = /^([0-9]+)(\\d{3})/;\n while (exp.test(x1))\n x1 = x1.replace(exp, \"$1\" + \",\" + \"$2\");\n return x1 + x2;\n}\n\nalert(\"123123\".toPrice()); //123,123.00\nalert(\"123123,316\".toPrice()); //123,123.32\nalert(\"12,312,313.33213\".toPrice()); //12,312,313.33\nalert(\"123.312.321,32132\".toPrice()); //123,312,321.32\n"
},
{
"answer_id": 11270819,
"author": "XML",
"author_id": 800457,
"author_profile": "https://Stackoverflow.com/users/800457",
"pm_score": 5,
"selected": false,
"text": "Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator, currencySymbol) {\n // check the args and supply defaults:\n decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces;\n decSeparator = decSeparator == undefined ? \".\" : decSeparator;\n thouSeparator = thouSeparator == undefined ? \",\" : thouSeparator;\n currencySymbol = currencySymbol == undefined ? \"$\" : currencySymbol;\n\n var n = this,\n sign = n < 0 ? \"-\" : \"\",\n i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + \"\",\n j = (j = i.length) > 3 ? j % 3 : 0;\n\n return sign + currencySymbol + (j ? i.substr(0, j) + thouSeparator : \"\") + i.substr(j).replace(/(\\d{3})(?=\\d)/g, \"$1\" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : \"\");\n};\n"
},
{
"answer_id": 11335085,
"author": "DanielEli",
"author_id": 273163,
"author_profile": "https://Stackoverflow.com/users/273163",
"pm_score": 2,
"selected": false,
"text": "Number::formatMoney = (decimalPlaces, decimalChar, thousandsChar) ->\n n = this\n c = decimalPlaces\n d = decimalChar\n t = thousandsChar\n c = (if isNaN(c = Math.abs(c)) then 2 else c)\n d = (if d is undefined then \".\" else d)\n t = (if t is undefined then \",\" else t)\n s = (if n < 0 then \"-\" else \"\")\n i = parseInt(n = Math.abs(+n or 0).toFixed(c)) + \"\"\n j = (if (j = i.length) > 3 then j % 3 else 0)\n s + (if j then i.substr(0, j) + t else \"\") + i.substr(j).replace(/(\\d{3})(?=\\d)/g, \"$1\" + t) + (if c then d + Math.abs(n - i).toFixed(c).slice(2) else \"\")\n"
},
{
"answer_id": 12698339,
"author": "adamwdraper",
"author_id": 875473,
"author_profile": "https://Stackoverflow.com/users/875473",
"pm_score": 5,
"selected": false,
"text": "numeral(23456.789).format('$0,0.00'); // = \"$23,456.79\"\n"
},
{
"answer_id": 12698442,
"author": "juanOS",
"author_id": 1357423,
"author_profile": "https://Stackoverflow.com/users/1357423",
"pm_score": 4,
"selected": false,
"text": "var formatter = new google.visualization.NumberFormat({\n prefix: '$',\n pattern: '#,###,###.##'\n});\n\nformatter.formatValue(1000000); // $ 1,000,000\n"
},
{
"answer_id": 12967079,
"author": "mendezcode",
"author_id": 235571,
"author_profile": "https://Stackoverflow.com/users/235571",
"pm_score": 1,
"selected": false,
"text": "function thousandCommas(num) {\n num = num.toString().split('.');\n var ints = num[0].split('').reverse();\n for (var out=[],len=ints.length,i=0; i < len; i++) {\n if (i > 0 && (i % 3) === 0) out.push(',');\n out.push(ints[i]);\n }\n out = out.reverse() && out.join('');\n if (num.length === 2) out += '.' + num[1];\n return out;\n}\n"
},
{
"answer_id": 14339482,
"author": "gavenkoa",
"author_id": 173149,
"author_profile": "https://Stackoverflow.com/users/173149",
"pm_score": 3,
"selected": false,
"text": "pp var NumUtil = {};\n\n/**\n Petty print 'num' wth exactly 'signif' digits.\n pp(123.45, 2) == \"120\"\n pp(0.012343, 3) == \"0.0123\"\n pp(1.2, 3) == \"1.20\"\n*/\nNumUtil.pp = function(num, signif) {\n if (typeof(num) !== \"number\")\n throw 'NumUtil.pp: num is not a number!';\n if (isNaN(num))\n throw 'NumUtil.pp: num is NaN!';\n if (num < 1e-15 || num > 1e15)\n return num;\n var r = Math.log(num)/Math.LN10;\n var dot = Math.floor(r) - (signif-1);\n r = r - Math.floor(r) + (signif-1);\n r = Math.round(Math.exp(r * Math.LN10)).toString();\n if (dot >= 0) {\n for (; dot > 0; dot -= 1)\n r += \"0\";\n return r;\n } else if (-dot >= r.length) {\n var p = \"0.\";\n for (; -dot > r.length; dot += 1) {\n p += \"0\";\n }\n return p+r;\n } else {\n return r.substring(0, r.length + dot) + \".\" + r.substring(r.length + dot);\n }\n}\n\n/** Append leading zeros up to 2 digits. */\nNumUtil.align2 = function(v) {\n if (v < 10)\n return \"0\"+v;\n return \"\"+v;\n}\n/** Append leading zeros up to 3 digits. */\nNumUtil.align3 = function(v) {\n if (v < 10)\n return \"00\"+v;\n else if (v < 100)\n return \"0\"+v;\n return \"\"+v;\n}\n\nNumUtil.integer = {};\n\n/** Round to integer and group by 3 digits. */\nNumUtil.integer.pp = function(num) {\n if (typeof(num) !== \"number\") {\n console.log(\"%s\", new Error().stack);\n throw 'NumUtil.integer.pp: num is not a number!';\n }\n if (isNaN(num))\n throw 'NumUtil.integer.pp: num is NaN!';\n if (num > 1e15)\n return num;\n if (num < 0)\n throw 'Negative num!';\n num = Math.round(num);\n var group = num % 1000;\n var integ = Math.floor(num / 1000);\n if (integ === 0) {\n return group;\n }\n num = NumUtil.align3(group);\n while (true) {\n group = integ % 1000;\n integ = Math.floor(integ / 1000);\n if (integ === 0)\n return group + \" \" + num;\n num = NumUtil.align3(group) + \" \" + num;\n }\n return num;\n}\n\nNumUtil.currency = {};\n\n/** Round to coins and group by 3 digits. */\nNumUtil.currency.pp = function(amount) {\n if (typeof(amount) !== \"number\")\n throw 'NumUtil.currency.pp: amount is not a number!';\n if (isNaN(amount))\n throw 'NumUtil.currency.pp: amount is NaN!';\n if (amount > 1e15)\n return amount;\n if (amount < 0)\n throw 'Negative amount!';\n if (amount < 1e-2)\n return 0;\n var v = Math.round(amount*100);\n var integ = Math.floor(v / 100);\n var frac = NumUtil.align2(v % 100);\n var group = integ % 1000;\n integ = Math.floor(integ / 1000);\n if (integ === 0) {\n return group + \".\" + frac;\n }\n amount = NumUtil.align3(group);\n while (true) {\n group = integ % 1000;\n integ = Math.floor(integ / 1000);\n if (integ === 0)\n return group + \" \" + amount + \".\" + frac;\n amount = NumUtil.align3(group) + \" \" + amount;\n }\n return amount;\n}\n"
},
{
"answer_id": 14428340,
"author": "VisioN",
"author_id": 1249581,
"author_profile": "https://Stackoverflow.com/users/1249581",
"pm_score": 11,
"selected": false,
"text": "(12345.67).toFixed(2).replace(/\\d(?=(\\d{3})+\\.)/g, '$&,'); // 12,345.67\n '$&,' 1 --> \"1.00\"\n12 --> \"12.00\"\n123 --> \"123.00\"\n1234 --> \"1,234.00\"\n12345 --> \"12,345.00\"\n123456 --> \"123,456.00\"\n1234567 --> \"1,234,567.00\"\n12345.67 --> \"12,345.67\"\n Number [0 .. n] [0 .. x] /**\n * Number.prototype.format(n, x)\n * \n * @param integer n: length of decimal\n * @param integer x: length of sections\n */\nNumber.prototype.format = function(n, x) {\n var re = '\\\\d(?=(\\\\d{' + (x || 3) + '})+' + (n > 0 ? '\\\\.' : '$') + ')';\n return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,');\n};\n\n1234..format(); // \"1,234\"\n12345..format(2); // \"12,345.00\"\n123456.7.format(3, 2); // \"12,34,56.700\"\n123456.789.format(2, 4); // \"12,3456.79\"\n /**\n * Number.prototype.format(n, x, s, c)\n * \n * @param integer n: length of decimal\n * @param integer x: length of whole part\n * @param mixed s: sections delimiter\n * @param mixed c: decimal delimiter\n */\nNumber.prototype.format = function(n, x, s, c) {\n var re = '\\\\d(?=(\\\\d{' + (x || 3) + '})+' + (n > 0 ? '\\\\D' : '$') + ')',\n num = this.toFixed(Math.max(0, ~~n));\n\n return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));\n};\n\n12345678.9.format(2, 3, '.', ','); // \"12.345.678,90\"\n123456.789.format(4, 4, ' ', ':'); // \"12 3456:7890\"\n12345678.9.format(0, 3, '-'); // \"12-345-679\"\n"
},
{
"answer_id": 14576179,
"author": "Kirk Bentley",
"author_id": 295694,
"author_profile": "https://Stackoverflow.com/users/295694",
"pm_score": 2,
"selected": false,
"text": "Number.implement('format', function(decPlaces, thouSeparator, decSeparator){\ndecPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces;\ndecSeparator = decSeparator === undefined ? '.' : decSeparator;\nthouSeparator = thouSeparator === undefined ? ',' : thouSeparator;\n\nvar num = this,\n sign = num < 0 ? '-' : '',\n i = parseInt(num = Math.abs(+num || 0).toFixed(decPlaces)) + '',\n j = (j = i.length) > 3 ? j % 3 : 0;\n\nreturn sign + (j ? i.substr(0, j) + thouSeparator : '') + i.substr(j).replace(/(\\d{3})(?=\\d)/g, '$1' + thouSeparator) + (decPlaces ? decSeparator + Math.abs(num - i).toFixed(decPlaces).slice(2) : '');\n});\n"
},
{
"answer_id": 14735423,
"author": "Jay Dansand",
"author_id": 198299,
"author_profile": "https://Stackoverflow.com/users/198299",
"pm_score": 4,
"selected": false,
"text": ".toCurrencyString() \"$\" $123 4567 $1,234,567 \"$\" Number.prototype.toCurrencyString = function(prefix, suffix) {\n if (typeof prefix === 'undefined') { prefix = '$'; }\n if (typeof suffix === 'undefined') { suffix = ''; }\n var _localeBug = new RegExp((1).toLocaleString().replace(/^1/, '').replace(/\\./, '\\\\.') + \"$\");\n return prefix + (~~this).toLocaleString().replace(_localeBug, '') + (this % 1).toFixed(2).toLocaleString().replace(/^[+-]?0+/,'') + suffix;\n }\n (number).toCurrencyString() var MyNumber = 123456789.125;\nalert(MyNumber.toCurrencyString()); // alerts \"$123,456,789.13\"\nMyNumber = -123.567;\nalert(MyNumber.toCurrencyString()); // alerts \"$-123.57\"\n"
},
{
"answer_id": 15538795,
"author": "kalisjoshua",
"author_id": 881558,
"author_profile": "https://Stackoverflow.com/users/881558",
"pm_score": 2,
"selected": false,
"text": "function format (val) {\n val = (+val).toLocaleString();\n val = (+val).toFixed(2);\n val += \"\";\n return val.replace(/(\\d)(?=(\\d{3})+(?:\\.\\d+)?$)/g, \"$1\" + format.thousands);\n}\n\n(function (isUS) {\n format.decimal = isUS ? \".\" : \",\";\n format.thousands = isUS ? \",\" : \".\";\n}((\"\" + (+(0.00).toLocaleString()).toFixed(2)).indexOf(\".\") > 0));\n [ \"\"\n , \"1\"\n , \"12\"\n , \"123\"\n , \"1234\"\n , \"12345\"\n , \"123456\"\n , \"1234567\"\n , \"12345678\"\n , \"123456789\"\n , \"1234567890\"\n , \".12\"\n , \"1.12\"\n , \"12.12\"\n , \"123.12\"\n , \"1234.12\"\n , \"12345.12\"\n , \"123456.12\"\n , \"1234567.12\"\n , \"12345678.12\"\n , \"123456789.12\"\n , \"1234567890.12\"\n , \"1234567890.123\"\n , \"1234567890.125\"\n].forEach(function (item) {\n console.log(format(item));\n});\n 0.00\n1.00\n12.00\n123.00\n1,234.00\n12,345.00\n123,456.00\n1,234,567.00\n12,345,678.00\n123,456,789.00\n1,234,567,890.00\n0.12\n1.12\n12.12\n123.12\n1,234.12\n12,345.12\n123,456.12\n1,234,567.12\n12,345,678.12\n123,456,789.12\n1,234,567,890.12\n1,234,567,890.12\n1,234,567,890.13\n"
},
{
"answer_id": 16233919,
"author": "aross",
"author_id": 1000608,
"author_profile": "https://Stackoverflow.com/users/1000608",
"pm_score": 11,
"selected": false,
"text": "// Create our number formatter.\nconst formatter = new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: 'USD',\n\n // These options are needed to round to whole numbers if that's what you want.\n //minimumFractionDigits: 0, // (this suffices for whole numbers, but will print 2500.10 as $2,500.1)\n //maximumFractionDigits: 0, // (causes 2500.99 to be printed as $2,501)\n});\n\nconsole.log(formatter.format(2500)); /* $2,500.00 */ undefined 'en-US' toLocaleString Intl Intl.NumberFormat Intl.NumberFormat toLocaleString console.log((2500).toLocaleString('en-US', {\n style: 'currency',\n currency: 'USD',\n})); /* $2,500.00 */ en-US"
},
{
"answer_id": 18245848,
"author": "Joseph Lennox",
"author_id": 1392539,
"author_profile": "https://Stackoverflow.com/users/1392539",
"pm_score": 2,
"selected": false,
"text": "var decimalCharacter = Number(\"1.1\").toLocaleString().substr(1,1);\nvar defaultCurrencyMarker = \"$\";\nfunction formatCurrency(number, currencyMarker) {\n if (typeof number != \"number\")\n number = parseFloat(number, 10);\n\n // if NaN is passed in or comes from the parseFloat, set it to 0.\n if (isNaN(number))\n number = 0;\n\n var sign = number < 0 ? \"-\" : \"\";\n number = Math.abs(number); // so our signage goes before the $ symbol.\n\n var integral = Math.floor(number);\n var formattedIntegral = integral.toLocaleString();\n\n // IE returns \"##.00\" while others return \"##\"\n formattedIntegral = formattedIntegral.split(decimalCharacter)[0];\n\n var decimal = Math.round((number - integral) * 100);\n return sign + (currencyMarker || defaultCurrencyMarker) +\n formattedIntegral +\n decimalCharacter +\n decimal.toString() + (decimal < 10 ? \"0\" : \"\");\n}\n var tests = [\n // [ input, expected result ]\n [123123, \"$123,123.00\"], // no decimal\n [123123.123, \"$123,123.12\"], // decimal rounded down\n [123123.126, \"$123,123.13\"], // decimal rounded up\n [123123.4, \"$123,123.40\"], // single decimal\n [\"123123\", \"$123,123.00\"], // repeat subset of the above using string input.\n [\"123123.123\", \"$123,123.12\"],\n [\"123123.126\", \"$123,123.13\"],\n [-123, \"-$123.00\"] // negatives\n];\n\nfor (var testIndex=0; testIndex < tests.length; testIndex++) {\n var test = tests[testIndex];\n var formatted = formatCurrency(test[0]);\n if (formatted == test[1]) {\n console.log(\"Test passed, \\\"\" + test[0] + \"\\\" resulted in \\\"\" + formatted + \"\\\"\");\n } else {\n console.error(\"Test failed. Expected \\\"\" + test[1] + \"\\\", got \\\"\" + formatted + \"\\\"\");\n }\n}\n"
},
{
"answer_id": 18994850,
"author": "Nick Grealy",
"author_id": 782034,
"author_profile": "https://Stackoverflow.com/users/782034",
"pm_score": 6,
"selected": false,
"text": "toLocaleString (2500).toLocaleString(\"en-GB\", {style: \"currency\", currency: \"GBP\", minimumFractionDigits: 2})\n console.log((2500).toLocaleString(\"en-ZA\", {style: \"currency\", currency: \"ZAR\", minimumFractionDigits: 2}))\n// -> R 2 500,00\nconsole.log((2500).toLocaleString(\"en-GB\", {style: \"currency\", currency: \"ZAR\", minimumFractionDigits: 2}))\n// -> ZAR 2,500.00"
},
{
"answer_id": 21255239,
"author": "Anunay",
"author_id": 674127,
"author_profile": "https://Stackoverflow.com/users/674127",
"pm_score": 2,
"selected": false,
"text": "function toCurrency(amount){\n return amount.replace(/(\\d)(?=(\\d\\d\\d)+(?!\\d))/g, \"$1,\");\n}\n\n// usage: toCurrency(3939920.3030);\n"
},
{
"answer_id": 23717185,
"author": "Steely Wing",
"author_id": 1877620,
"author_profile": "https://Stackoverflow.com/users/1877620",
"pm_score": 4,
"selected": false,
"text": "if (typeof Number.prototype.format === 'undefined') {\n Number.prototype.format = function (precision) {\n if (!isFinite(this)) {\n return this.toString();\n }\n\n var a = this.toFixed(precision).split('.');\n a[0] = a[0].replace(/\\d(?=(\\d{3})+$)/g, '$&,');\n return a.join('.');\n }\n}\n if (typeof Number.prototype.format === 'undefined') {\n Number.prototype.format = function (precision) {\n if (!isFinite(this)) {\n return this.toString();\n }\n\n var a = this.toFixed(precision).split('.'),\n // Skip the '-' sign\n head = Number(this < 0);\n\n // Skip the digits that's before the first thousands separator\n head += (a[0].length - head) % 3 || 3;\n\n a[0] = a[0].slice(0, head) + a[0].slice(head).replace(/\\d{3}/g, ',$&');\n return a.join('.');\n };\n}\n if (typeof Number.prototype.format === 'undefined') {\n Number.prototype.format = function (precision) {\n if (!isFinite(this)) {\n return this.toString();\n }\n\n var a = this.toFixed(precision).split('.');\n\n a[0] = a[0]\n .split('').reverse().join('')\n .replace(/\\d{3}(?=\\d)/g, '$&,')\n .split('').reverse().join('');\n\n return a.join('.');\n };\n}\n if (typeof Number.prototype.format === 'undefined') {\n Number.prototype.format = function (precision) {\n if (!isFinite(this)) {\n return this.toString();\n }\n\n var a = this.toFixed(precision).split('');\n a.push('.');\n\n var i = a.indexOf('.') - 3;\n while (i > 0 && a[i-1] !== '-') {\n a.splice(i, 0, ',');\n i -= 3;\n }\n\n a.pop();\n return a.join('');\n };\n}\n console.log('======== Demo ========')\nconsole.log(\n (1234567).format(0),\n (1234.56).format(2),\n (-1234.56).format(0)\n);\nvar n = 0;\nfor (var i=1; i<20; i++) {\n n = (n * 10) + (i % 10)/100;\n console.log(n.format(2), (-n).format(2));\n}\n replace() 123456.78.format(2).replace(',', ' ').replace('.', ' ');\n function assertEqual(a, b) {\n if (a !== b) {\n throw a + ' !== ' + b;\n }\n}\n\nfunction test(format_function) {\n console.log(format_function);\n assertEqual('NaN', format_function.call(NaN, 0))\n assertEqual('Infinity', format_function.call(Infinity, 0))\n assertEqual('-Infinity', format_function.call(-Infinity, 0))\n\n assertEqual('0', format_function.call(0, 0))\n assertEqual('0.00', format_function.call(0, 2))\n assertEqual('1', format_function.call(1, 0))\n assertEqual('-1', format_function.call(-1, 0))\n\n // Decimal padding\n assertEqual('1.00', format_function.call(1, 2))\n assertEqual('-1.00', format_function.call(-1, 2))\n\n // Decimal rounding\n assertEqual('0.12', format_function.call(0.123456, 2))\n assertEqual('0.1235', format_function.call(0.123456, 4))\n assertEqual('-0.12', format_function.call(-0.123456, 2))\n assertEqual('-0.1235', format_function.call(-0.123456, 4))\n\n // Thousands separator\n assertEqual('1,234', format_function.call(1234.123456, 0))\n assertEqual('12,345', format_function.call(12345.123456, 0))\n assertEqual('123,456', format_function.call(123456.123456, 0))\n assertEqual('1,234,567', format_function.call(1234567.123456, 0))\n assertEqual('12,345,678', format_function.call(12345678.123456, 0))\n assertEqual('123,456,789', format_function.call(123456789.123456, 0))\n assertEqual('-1,234', format_function.call(-1234.123456, 0))\n assertEqual('-12,345', format_function.call(-12345.123456, 0))\n assertEqual('-123,456', format_function.call(-123456.123456, 0))\n assertEqual('-1,234,567', format_function.call(-1234567.123456, 0))\n assertEqual('-12,345,678', format_function.call(-12345678.123456, 0))\n assertEqual('-123,456,789', format_function.call(-123456789.123456, 0))\n\n // Thousands separator and decimal\n assertEqual('1,234.12', format_function.call(1234.123456, 2))\n assertEqual('12,345.12', format_function.call(12345.123456, 2))\n assertEqual('123,456.12', format_function.call(123456.123456, 2))\n assertEqual('1,234,567.12', format_function.call(1234567.123456, 2))\n assertEqual('12,345,678.12', format_function.call(12345678.123456, 2))\n assertEqual('123,456,789.12', format_function.call(123456789.123456, 2))\n assertEqual('-1,234.12', format_function.call(-1234.123456, 2))\n assertEqual('-12,345.12', format_function.call(-12345.123456, 2))\n assertEqual('-123,456.12', format_function.call(-123456.123456, 2))\n assertEqual('-1,234,567.12', format_function.call(-1234567.123456, 2))\n assertEqual('-12,345,678.12', format_function.call(-12345678.123456, 2))\n assertEqual('-123,456,789.12', format_function.call(-123456789.123456, 2))\n}\n\nconsole.log('======== Testing ========');\ntest(Number.prototype.format);\ntest(Number.prototype.format1);\ntest(Number.prototype.format2);\ntest(Number.prototype.format3);\n function benchmark(f) {\n var start = new Date().getTime();\n f();\n return new Date().getTime() - start;\n}\n\nfunction benchmark_format(f) {\n console.log(f);\n time = benchmark(function () {\n for (var i = 0; i < 100000; i++) {\n f.call(123456789, 0);\n f.call(123456789, 2);\n }\n });\n console.log(time.format(0) + 'ms');\n}\n\n// If not using async, the browser will stop responding while running.\n// This will create a new thread to benchmark\nasync = [];\nfunction next() {\n setTimeout(function () {\n f = async.shift();\n f && f();\n next();\n }, 10);\n}\n\nconsole.log('======== Benchmark ========');\nasync.push(function () { benchmark_format(Number.prototype.format); });\nnext();\n"
},
{
"answer_id": 23747994,
"author": "Chad Kuehn",
"author_id": 1069995,
"author_profile": "https://Stackoverflow.com/users/1069995",
"pm_score": 3,
"selected": false,
"text": "function formatCurrency(total) {\n var neg = false;\n if(total < 0) {\n neg = true;\n total = Math.abs(total);\n }\n return (neg ? \"-$\" : '$') + parseFloat(total, 10).toFixed(2).replace(/(\\d)(?=(\\d{3})+\\.)/g, \"$1,\").toString();\n}\n"
},
{
"answer_id": 24428097,
"author": "Tom",
"author_id": 1937025,
"author_profile": "https://Stackoverflow.com/users/1937025",
"pm_score": 2,
"selected": false,
"text": "Number.prototype.formatNumber = function(decPlaces, thouSeparator, decSeparator) {\n decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces;\n decSeparator = decSeparator == undefined ? \".\" : decSeparator;\n thouSeparator = thouSeparator == undefined ? \",\" : thouSeparator;\n\n var n = this.toFixed(decPlaces);\n if (decPlaces) {\n var i = n.substr(0, n.length - (decPlaces + 1));\n var j = decSeparator + n.substr(-decPlaces);\n } else {\n i = n;\n j = '';\n }\n\n function reverse(str) {\n var sr = '';\n for (var l = str.length - 1; l >= 0; l--) {\n sr += str.charAt(l);\n }\n return sr;\n }\n\n if (parseInt(i)) {\n i = reverse(reverse(i).replace(/(\\d{3})(?=\\d)/g, \"$1\" + thouSeparator));\n }\n return i + j;\n};\n var sum = 123456789.5698;\nvar formatted = '$' + sum.formatNumber(2, ',', '.'); // \"$123,456,789.57\"\n"
},
{
"answer_id": 25753822,
"author": "Tomas Kubes",
"author_id": 518530,
"author_profile": "https://Stackoverflow.com/users/518530",
"pm_score": 1,
"selected": false,
"text": "function formatPriceUSD(price) {\n var strPrice = price.toFixed(2).toString();\n var a = strPrice.split('');\n\n if (price > 1000000000)\n a.splice(a.length - 12, 0, ',');\n\n if (price > 1000000)\n a.splice(a.length - 9, 0, ',');\n\n if (price > 1000)\n a.splice(a.length - 6, 0, ',');\n\n return '$' + a.join(\"\");\n}\n"
},
{
"answer_id": 25755921,
"author": "iBet7o",
"author_id": 2109568,
"author_profile": "https://Stackoverflow.com/users/2109568",
"pm_score": 3,
"selected": false,
"text": "var number = 3500;\nalert(new Intl.NumberFormat().format(number));\n// → \"3,500\" if in US English locale\n"
},
{
"answer_id": 26745078,
"author": "Daniel Barbalace",
"author_id": 4076267,
"author_profile": "https://Stackoverflow.com/users/4076267",
"pm_score": 7,
"selected": false,
"text": "-123 amount.toLocaleString('en-US', { style: 'currency', currency: 'USD' });\n \"-$123.00\""
},
{
"answer_id": 28215542,
"author": "mp31415",
"author_id": 194715,
"author_profile": "https://Stackoverflow.com/users/194715",
"pm_score": 2,
"selected": false,
"text": "n.toFixed(2).replace(/\\d(?=(\\d{3})+\\.)/g, '$&,');\n var re = /\\d(?=(\\d{3})+\\.)/g;\nvar subst = '$&,';\nn.toFixed(2).replace(re, subst);\n re \\d ?= ( )+ \\d{3} \\. g subst $& string.replace var re2 = /\\d(?=(\\d{3})+$)/g;\n $ \\. toFixed(0) n.toFixed(0).replace(/\\d(?=(\\d{3})+$)/g, '$&,');\n 1234567.89 -> 1,234,567\n $ \\b"
},
{
"answer_id": 28640113,
"author": "user2807653",
"author_id": 2807653,
"author_profile": "https://Stackoverflow.com/users/2807653",
"pm_score": 2,
"selected": false,
"text": "function Format_Numb(fmt){\n var decimals = isNaN(decimals) ? 2 : Math.abs(decimals);\n if(typeof decSgn === \"undefined\") decSgn = \".\";\n if(typeof kommaSgn === \"undefined\") kommaSgn= \",\";\n\n var s3digits = /(\\d{1,3}(?=(\\d{3})+(?=[.]|$))|(?:[.]\\d*))/g;\n var dflt_nk = \"00000000\".substring(0, decimals);\n\n //--------------------------------\n // handler for pattern: \"%m\"\n var _f_money = function(v_in){\n var v = v_in.toFixed(decimals);\n var add_nk = \",00\";\n var arr = v.split(\".\");\n return arr[0].toString().replace(s3digits, function ($0) {\n return ($0.charAt(0) == \".\")\n ? ((add_nk = \"\"), (kommaSgn + $0.substring(1)))\n : ($0 + decSgn);\n })\n + ((decimals > 0)\n ? (kommaSgn\n + (\n (arr.length > 1)\n ? arr[1]\n : dflt_nk\n )\n )\n : \"\"\n );\n }\n\n // handler for pattern: \"%<len>[.<prec>]f\"\n var _f_flt = function(v_in, l, prec){\n var v = (typeof prec !== \"undefined\") ? v_in.toFixed(prec) : v_in;\n return ((typeof l !== \"undefined\") && ((l=l-v.length) > 0))\n ? (Array(l+1).join(\" \") + v)\n : v;\n }\n\n // handler for pattern: \"%<len>x\"\n var _f_hex = function(v_in, l, flUpper){\n var v = Math.round(v_in).toString(16);\n if(flUpper) v = v.toUpperCase();\n return ((typeof l !== \"undefined\") && ((l=l-v.length) > 0))\n ? (Array(l+1).join(\"0\") + v)\n : v;\n }\n\n //...can be extended..., just add the function, for example: var _f_octal = function( v_in,...){\n //--------------------------------\n\n if(typeof(fmt) !== \"undefined\"){\n //...can be extended..., just add the char, for example \"O\": MFX -> MFXO\n var rpatt = /(?:%([^%\"MFX]*)([MFX]))|(?:\"([^\"]*)\")|(\"|%%)/gi;\n var _qu = \"\\\"\";\n var _mask_qu = \"\\\\\\\"\";\n var str = fmt.toString().replace(rpatt, function($0, $1, $2, $3, $4){\n var f;\n if(typeof $1 !== \"undefined\"){\n switch($2.toUpperCase()){\n case \"M\": f = \"_f_money(v)\"; break;\n\n case \"F\": var n_dig0, n_dig1;\n var re_flt =/^(?:(\\d))*(?:[.](\\d))*$/;\n $1.replace(re_flt, function($0, $1, $2){\n n_dig0 = $1;\n n_dig1 = $2;\n });\n f = \"_f_flt(v, \" + n_dig0 + \",\" + n_dig1 + \")\"; break;\n\n case \"X\": var n_dig = \"undefined\";\n var re_flt = /^(\\d*)$/;\n $1.replace(re_flt, function($0){\n if($0 != \"\") n_dig = $0;\n });\n f = \"_f_hex(v, \" + n_dig + \",\" + ($2==\"X\") + \")\"; break;\n //...can be extended..., for example: case \"O\":\n }\n return \"\\\"+\"+f+\"+\\\"\";\n } else if(typeof $3 !== \"undefined\"){\n return _mask_qu + $3 + _mask_qu;\n } else {\n return ($4 == _qu) ? _mask_qu : $4.charAt(0);\n }\n });\n\n var cmd = \"return function(v){\"\n + \"if(typeof v === \\\"undefined\\\")return \\\"\\\";\" // null returned as empty string\n + \"if(!v.toFixed) return v.toString();\" // not numb returned as string\n + \"return \\\"\" + str + \"\\\";\"\n + \"}\";\n\n //...can be extended..., just add the function name in the 2 places:\n return new Function(\"_f_money,_f_flt,_f_hex\", cmd)(_f_money,_f_flt,_f_hex);\n }\n}\n %[<len>][.<prec>]f float, example \"%f\", \"%8.2d\", \"%.3f\"\n%m money\n%[<len>]x hexadecimal lower case, example \"%x\", \"%8x\"\n%[<len>]X hexadecimal upper case, example \"%X\", \"%8X\"\n // var formatter = Format_Numb( \"%m €\");\n// simple example for Euro...\n\n// but we use a complex example:\n\nvar formatter = Format_Numb(\"a%%%3mxx \\\"zz\\\"%8.2f°\\\" >0x%8X<\");\n\n// formatter is now a function, which can be used more than once (this is an example, that can be tested:)\n\nvar v1 = formatter(1897654.8198344);\n\nvar v2 = formatter(4.2);\n\n... (and thousands of rows)\n _f_money Number.prototype.format_euro = (function(formatter){\n return function(){ return formatter(this); }})\n(Format_Numb( \"%m €\"));\n\nvar v_euro = (8192.3282).format_euro(); // results: 8.192,33 €\n\nNumber.prototype.format_hex = (function(formatter){\n return function(){ return formatter(this); }})\n(Format_Numb( \"%4x\"));\n\nvar v_hex = (4.3282).format_hex();\n"
},
{
"answer_id": 29471888,
"author": "rab",
"author_id": 1722625,
"author_profile": "https://Stackoverflow.com/users/1722625",
"pm_score": 2,
"selected": false,
"text": "function currencyFormat(no) {\n var ar = (+no).toFixed(2).split('.');\n return [\n numberFormat(ar[0] | 0),\n '.',\n ar[1]\n ].join('');\n}\n\n\nfunction numberFormat(no) {\n var str = no + '';\n var ar = [];\n var i = str.length -1;\n\n while(i >= 0) {\n ar.push((str[i-2] || '') + (str[i-1] || '') + (str[i] || ''));\n i = i-3;\n }\n return ar.reverse().join(',');\n}\n console.log(\n currencyFormat(1),\n currencyFormat(1200),\n currencyFormat(123),\n currencyFormat(9870000),\n currencyFormat(12345),\n currencyFormat(123456.232)\n)\n"
},
{
"answer_id": 30033551,
"author": "Ken Palmer",
"author_id": 993856,
"author_profile": "https://Stackoverflow.com/users/993856",
"pm_score": 3,
"selected": false,
"text": "var formatMoney = function (value) {\n // Convert the value to a floating point number in case it arrives as a string.\n var numeric = parseFloat(value);\n // Specify the local currency.\n return numeric.toLocaleString('USD', { style: 'currency', currency: \"USD\", minimumFractionDigits: 2, maximumFractionDigits: 2 });\n}\n"
},
{
"answer_id": 33286686,
"author": "jacob",
"author_id": 1784298,
"author_profile": "https://Stackoverflow.com/users/1784298",
"pm_score": 3,
"selected": false,
"text": "function centsToDollaString(x){\n var cents = x + \"\"\n while(cents.length < 4){\n cents = \"0\" + cents;\n }\n var dollars = cents.substr(0,cents.length - 2)\n var decimal = cents.substr(cents.length - 2, 2)\n while(dollars.length % 3 != 0){\n dollars = \"0\" + dollars;\n }\n str = dollars.replace(/(\\d{3})(?=\\d)/g, \"$1\" + \",\").replace(/^0*(?=.)/, \"\");\n return \"$\" + str + \".\" + decimal;\n}\n"
},
{
"answer_id": 34686753,
"author": "Diego Fernando Villarroel Diaz",
"author_id": 5236798,
"author_profile": "https://Stackoverflow.com/users/5236798",
"pm_score": 2,
"selected": false,
"text": "function toMoney(amount) {\n neg = amount.charAt(0);\n amount = amount.replace(/\\D/g, '');\n amount = amount.replace(/\\./g, '');\n amount = amount.replace(/\\-/g, '');\n\n var numAmount = new Number(amount);\n amount = numAmount.toFixed(0).replace(/./g, function(c, i, a) {\n return i > 0 && c !== \",\" && (a.length - i) % 3 === 0 ? \".\" + c : c;\n });\n\n if(neg == '-')\n return neg + amount;\n else\n return amount;\n}\n <html>\n<head>\n <script language==\"Javascript\">\n function isNumber(evt) {\n var theEvent = evt || window.event;\n var key = theEvent.keyCode || theEvent.which;\n key = String.fromCharCode(key);\n if (key.length == 0)\n return;\n var regex = /^[0-9\\-\\b]+$/;\n if (!regex.test(key)) {\n theEvent.returnValue = false;\n if (theEvent.preventDefault)\n theEvent.preventDefault();\n }\n }\n\n function toMoney(amount) {\n neg = amount.charAt(0);\n amount = amount.replace(/\\D/g, '');\n amount = amount.replace(/\\./g, '');\n amount = amount.replace(/\\-/g, '');\n\n var numAmount = new Number(amount);\n amount = numAmount.toFixed(0).replace(/./g, function(c, i, a) {\n return i > 0 && c !== \",\" && (a.length - i) % 3 === 0 ? \".\" + c : c;\n });\n\n if(neg == '-')\n return neg + amount;\n else\n return amount;\n }\n\n function clearText(inTxt, newTxt, outTxt) {\n inTxt = inTxt.trim();\n newTxt = newTxt.trim();\n if(inTxt == '' || inTxt == newTxt)\n return outTxt;\n\n return inTxt;\n }\n\n function fillText(inTxt, outTxt) {\n inTxt = inTxt.trim();\n if(inTxt != '')\n outTxt = inTxt;\n\n return outTxt;\n }\n </script>\n</head>\n\n<body>\n $ <input name=reca2 id=reca2 type=text value=\"0\" onFocus=\"this.value = clearText(this.value, '0', '');\" onblur=\"this.value = fillText(this.value, '0'); this.value = toMoney(this.value);\" onKeyPress=\"isNumber(event);\" style=\"width:80px;\" />\n</body>\n\n</html>\n"
},
{
"answer_id": 37626980,
"author": "Faysal Haque",
"author_id": 1993427,
"author_profile": "https://Stackoverflow.com/users/1993427",
"pm_score": 4,
"selected": false,
"text": "// Default usage:\naccounting.formatMoney(12345678); // $12,345,678.00\n\n// European formatting (custom symbol and separators), can also use options object as second parameter:\naccounting.formatMoney(4999.99, \"€\", 2, \".\", \",\"); // €4.999,99\n\n// Negative values can be formatted nicely:\naccounting.formatMoney(-500000, \"£ \", 0); // £ -500,000\n\n// Simple `format` string allows control of symbol position (%v = value, %s = symbol):\naccounting.formatMoney(5318008, { symbol: \"GBP\", format: \"%v %s\" }); // 5,318,008.00 GBP\n\n// Euro currency symbol to the right\naccounting.formatMoney(5318008, {symbol: \"€\", precision: 2, thousand: \".\", decimal : \",\", format: \"%v%s\"}); // 1.008,00€ "
},
{
"answer_id": 39782793,
"author": "James Eames",
"author_id": 6896525,
"author_profile": "https://Stackoverflow.com/users/6896525",
"pm_score": 2,
"selected": false,
"text": "OSREC.CurrencyFormatter.format(2534234, { currency: 'INR' }); // Returns ₹ 25,34,234.00 OSREC.CurrencyFormatter.format(2534234, { currency: 'EUR' }); // Returns 2.534.234,00 € OSREC.CurrencyFormatter.format(2534234, { currency: 'EUR', locale: 'fr' }); // Returns 2 534 234,00 €"
},
{
"answer_id": 40079019,
"author": "synthet1c",
"author_id": 1733478,
"author_profile": "https://Stackoverflow.com/users/1733478",
"pm_score": 5,
"selected": false,
"text": "function moneyFormat(price, sign = '$') {\n const pieces = parseFloat(price).toFixed(2).split('')\n let ii = pieces.length - 3\n while ((ii-=3) > 0) {\n pieces.splice(ii, 0, ',')\n }\n return sign + pieces.join('')\n}\n\nconsole.log(\n moneyFormat(100),\n moneyFormat(1000),\n moneyFormat(10000.00),\n moneyFormat(1000000000000000000)\n) // higher order function that takes options then a price and will return the formatted price\nconst makeMoneyFormatter = ({\n sign = '$',\n delimiter = ',',\n decimal = '.',\n append = false,\n precision = 2,\n round = true,\n custom\n} = {}) => value => {\n\n const e = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000]\n\n value = round\n ? (Math.round(value * e[precision]) / e[precision])\n : parseFloat(value)\n\n const pieces = value\n .toFixed(precision)\n .replace('.', decimal)\n .split('')\n\n let ii = pieces.length - (precision ? precision + 1 : 0)\n\n while ((ii-=3) > 0) {\n pieces.splice(ii, 0, delimiter)\n }\n\n if (typeof custom === 'function') {\n return custom({\n sign,\n float: value,\n value: pieces.join('')\n })\n }\n\n return append\n ? pieces.join('') + sign\n : sign + pieces.join('')\n}\n\n// create currency converters with the correct formatting options\nconst formatDollar = makeMoneyFormatter()\nconst formatPound = makeMoneyFormatter({\n sign: '£',\n precision: 0\n})\nconst formatEuro = makeMoneyFormatter({\n sign: '€',\n delimiter: '.',\n decimal: ',',\n append: true\n})\n\nconst customFormat = makeMoneyFormatter({\n round: false,\n custom: ({ value, float, sign }) => `SALE:$${value}USD`\n})\n\nconsole.log(\n formatPound(1000),\n formatDollar(10000.0066),\n formatEuro(100000.001),\n customFormat(999999.555)\n)"
},
{
"answer_id": 40534670,
"author": "Daniel Campos",
"author_id": 1790336,
"author_profile": "https://Stackoverflow.com/users/1790336",
"pm_score": 2,
"selected": false,
"text": "var number = slimFormatter.currency(2000.54);\n"
},
{
"answer_id": 40753048,
"author": "Choylton B. Higginbottom",
"author_id": 949598,
"author_profile": "https://Stackoverflow.com/users/949598",
"pm_score": 2,
"selected": false,
"text": "function numberFormatter (num) {\n console.log(num)\n var wholeAndDecimal = String(num.toFixed(2)).split(\".\");\n console.log(wholeAndDecimal)\n var reversedWholeNumber = Array.from(wholeAndDecimal[0]).reverse();\n var formattedOutput = [];\n\n reversedWholeNumber.forEach( (digit, index) => {\n formattedOutput.push(digit);\n if ((index + 1) % 3 === 0 && index < reversedWholeNumber.length - 1) {\n formattedOutput.push(\",\");\n }\n })\n\n formattedOutput = formattedOutput.reverse().join('') + \".\" + wholeAndDecimal[1];\n\n return formattedOutput;\n}\n"
},
{
"answer_id": 49688690,
"author": "Nick",
"author_id": 9473764,
"author_profile": "https://Stackoverflow.com/users/9473764",
"pm_score": 2,
"selected": false,
"text": "Number.prototype.formatCurrency = function() { return this.toFixed(2).toString().split(/[-.]/).reverse().reduceRight(function (t, c, i) { return (i == 2) ? '-' + t : (i == 1) ? t + c.replace(/(\\d)(?=(\\d{3})+$)/g, '$1,') : t + '.' + c; }, '$'); }\n , . Number.prototype.formatCurrency = function(thou = ',', dec = '.', sym = '$') { return this.toFixed(2).toString().split(/[-.]/).reverse().reduceRight(function (t, c, i) { return (i == 2) ? '-' + t : (i == 1) ? t + c.replace(/(\\d)(?=(\\d{3})+$)/g, '$1' + thou) : t + dec + c; }, sym); }\n\nconsole.log((4215.57).formatCurrency())\n$4,215.57\nconsole.log((4216635.57).formatCurrency('.', ','))\n$4.216.635,57\nconsole.log((4216635.57).formatCurrency('.', ',', \"\\u20AC\"))\n€4.216.635,57\n console.log((-6635.574).formatCurrency('.', ',', \"\\u20AC\"))\n-€6.635,57\nconsole.log((-1066.507).formatCurrency())\n-$1,066.51\n console.log((1234.586).formatCurrency(',','.',''))\n1,234.59\nconsole.log((-7890123.456).formatCurrency(',','.',''))\n-7,890,123.46\nconsole.log((1237890.456).formatCurrency('.',',',''))\n1.237.890,46\n"
},
{
"answer_id": 51597446,
"author": "Nicolas Giszpenc",
"author_id": 3727524,
"author_profile": "https://Stackoverflow.com/users/3727524",
"pm_score": 2,
"selected": false,
"text": "function formatDollar(amount) {\n var dollar = Number(amount).toLocaleString(\"us\", \"currency\");\n // Decimals\n var arrAmount = dollar.split(\".\");\n if (arrAmount.length==2) {\n var decimal = arrAmount[1];\n if (decimal.length==1) {\n arrAmount[1] += \"0\";\n }\n }\n if (arrAmount.length==1) {\n arrAmount.push(\"00\");\n }\n\n return \"$\" + arrAmount.join(\".\");\n}\n\n\nconsole.log(formatDollar(\"1812.2\");\n"
},
{
"answer_id": 54274936,
"author": "Adam Pery",
"author_id": 1500836,
"author_profile": "https://Stackoverflow.com/users/1500836",
"pm_score": 4,
"selected": false,
"text": "Number(value)\n .toFixed(2)\n .replace(/(\\d)(?=(\\d{3})+(?!\\d))/g, \"$1,\")"
},
{
"answer_id": 57726061,
"author": "Dinesh Lomte",
"author_id": 2436314,
"author_profile": "https://Stackoverflow.com/users/2436314",
"pm_score": 1,
"selected": false,
"text": "<tr>\n <td>\n <label class=\"control-label\">\n Number Field:\n </label>\n <div class=\"inner-addon right-addon\">\n <input type=\"text\" id=\"numberField\"\n name=\"numberField\"\n class=\"form-control\"\n autocomplete=\"off\"\n maxlength=\"17\"\n data-rule-required=\"true\"\n data-msg-required=\"Cannot be blank.\"\n data-msg-maxlength=\"Exceeding the maximum limit of 13 digits. Example: 1234567890123\"\n data-rule-numberExceedsMaxLimit=\"en\"\n data-msg-numberExceedsMaxLimit=\"Exceeding the maximum limit of 13 digits. Example: 1234567890123\"\n onkeydown=\"return isNumber(event, 'en')\"\n onkeyup=\"return updateField(this)\"\n onblur=\"numberFormatter(this,\n 'en',\n 'Invalid character(s) found. Please enter valid characters.')\">\n </div>\n </td>\n</tr>\n\n<tr>\n <td>\n <label class=\"control-label\">\n Decimal Field:\n </label>\n <div class=\"inner-addon right-addon\">\n <input type=\"text\" id=\"decimalField\"\n name=\"decimalField\"\n class=\"form-control\"\n autocomplete=\"off\"\n maxlength=\"20\"\n data-rule-required=\"true\"\n data-msg-required=\"Cannot be blank.\"\n data-msg-maxlength=\"Exceeding the maximum limit of 16 digits. Example: 1234567890123.00\"\n data-rule-decimalExceedsMaxLimit=\"en\"\n data-msg-decimalExceedsMaxLimit=\"Exceeding the maximum limit of 16 digits. Example: 1234567890123.00\"\n onkeydown=\"return isDecimal(event, 'en')\"\n onkeyup=\"return updateField(this)\"\n onblur=\"decimalFormatter(this,\n 'en',\n 'Invalid character(s) found. Please enter valid characters.')\">\n </div>\n </td>\n</tr>\n /*\n * @author: dinesh.lomte\n */\n/* Holds the maximum limit of digits to be entered in number field. */\nvar numericMaxLimit = 13;\n/* Holds the maximum limit of digits to be entered in decimal field. */\nvar decimalMaxLimit = 16;\n\n/**\n *\n * @param {type} value\n * @param {type} locale\n * @returns {Boolean}\n */\nparseDecimal = function(value, locale) {\n\n value = value.trim();\n if (isNull(value)) {\n return 0.00;\n }\n if (isNull(locale)) {\n return value;\n }\n if (getNumberFormat(locale)[0] === '.') {\n value = value.replace(/\\./g, '');\n } else {\n value = value.replace(\n new RegExp(getNumberFormat(locale)[0], 'g'), '');\n }\n if (getNumberFormat(locale)[1] === ',') {\n value = value.replace(\n new RegExp(getNumberFormat(locale)[1], 'g'), '.');\n }\n return value;\n};\n\n/**\n *\n * @param {type} element\n * @param {type} locale\n * @param {type} nanMessage\n * @returns {Boolean}\n */\ndecimalFormatter = function (element, locale, nanMessage) {\n\n showErrorMessage(element.id, false, null);\n if (isNull(element.id) || isNull(element.value) || isNull(locale)) {\n return true;\n }\n var value = element.value.trim();\n value = value.replace(/\\s/g, '');\n value = parseDecimal(value, locale);\n var numberFormatObj = new Intl.NumberFormat(locale,\n { minimumFractionDigits: 2,\n maximumFractionDigits: 2\n }\n );\n if (numberFormatObj.format(value) === 'NaN') {\n showErrorMessage(element.id, true, nanMessage);\n setFocus(element.id);\n return false;\n }\n element.value = numberFormatObj.format(value);\n return true;\n};\n\n/**\n *\n * @param {type} element\n * @param {type} locale\n * @param {type} nanMessage\n * @returns {Boolean}\n */\nnumberFormatter = function (element, locale, nanMessage) {\n\n showErrorMessage(element.id, false, null);\n if (isNull(element.id) || isNull(element.value) || isNull(locale)) {\n return true;\n }\n var value = element.value.trim();\n var format = getNumberFormat(locale);\n if (hasDecimal(value, format[1])) {\n showErrorMessage(element.id, true, nanMessage);\n setFocus(element.id);\n return false;\n }\n value = value.replace(/\\s/g, '');\n value = parseNumber(value, locale);\n var numberFormatObj = new Intl.NumberFormat(locale,\n { minimumFractionDigits: 0,\n maximumFractionDigits: 0\n }\n );\n if (numberFormatObj.format(value) === 'NaN') {\n showErrorMessage(element.id, true, nanMessage);\n setFocus(element.id);\n return false;\n }\n element.value =\n numberFormatObj.format(value);\n return true;\n};\n\n/**\n *\n * @param {type} id\n * @param {type} flag\n * @param {type} message\n * @returns {undefined}\n */\nshowErrorMessage = function(id, flag, message) {\n\n if (flag) {\n // only add if not added\n if ($('#'+id).parent().next('.app-error-message').length === 0) {\n var errorTag = '<div class=\\'app-error-message\\'>' + message + '</div>';\n $('#'+id).parent().after(errorTag);\n }\n } else {\n // remove it\n $('#'+id).parent().next(\".app-error-message\").remove();\n }\n};\n\n/**\n *\n * @param {type} id\n * @returns\n */\nsetFocus = function(id) {\n\n id = id.trim();\n if (isNull(id)) {\n return;\n }\n setTimeout(function() {\n document.getElementById(id).focus();\n }, 10);\n};\n\n/**\n *\n * @param {type} value\n * @param {type} locale\n * @returns {Array}\n */\nparseNumber = function(value, locale) {\n\n value = value.trim();\n if (isNull(value)) {\n return 0;\n }\n if (isNull(locale)) {\n return value;\n }\n if (getNumberFormat(locale)[0] === '.') {\n return value.replace(/\\./g, '');\n }\n return value.replace(\n new RegExp(getNumberFormat(locale)[0], 'g'), '');\n};\n\n/**\n *\n * @param {type} locale\n * @returns {Array}\n */\ngetNumberFormat = function(locale) {\n\n var format = [];\n var numberFormatObj = new Intl.NumberFormat(locale,\n { minimumFractionDigits: 2,\n maximumFractionDigits: 2\n }\n );\n var value = numberFormatObj.format('132617.07');\n format[0] = value.charAt(3);\n format[1] = value.charAt(7);\n return format;\n};\n\n/**\n *\n * @param {type} value\n * @param {type} fractionFormat\n * @returns {Boolean}\n */\nhasDecimal = function(value, fractionFormat) {\n\n value = value.trim();\n if (isNull(value) || isNull(fractionFormat)) {\n return false;\n }\n if (value.indexOf(fractionFormat) >= 1) {\n return true;\n }\n};\n\n/**\n *\n * @param {type} event\n * @param {type} locale\n * @returns {Boolean}\n */\nisNumber = function(event, locale) {\n\n var keyCode = event.which ? event.which : event.keyCode;\n // Validating if user has pressed shift character\n if (keyCode === 16) {\n return false;\n }\n if (isNumberKey(keyCode)) {\n return true;\n }\n var numberFormatter = [32, 110, 188, 190];\n if (keyCode === 32\n && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) {\n return true;\n }\n if (numberFormatter.indexOf(keyCode) >= 0\n && getNumberFormat(locale)[0] === getFormat(keyCode)) {\n return true;\n }\n return false;\n};\n\n/**\n *\n * @param {type} event\n * @param {type} locale\n * @returns {Boolean}\n */\nisDecimal = function(event, locale) {\n\n var keyCode = event.which ? event.which : event.keyCode;\n // Validating if user has pressed shift character\n if (keyCode === 16) {\n return false;\n }\n if (isNumberKey(keyCode)) {\n return true;\n }\n var numberFormatter = [32, 110, 188, 190];\n if (keyCode === 32\n && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) {\n return true;\n }\n if (numberFormatter.indexOf(keyCode) >= 0\n && (getNumberFormat(locale)[0] === getFormat(keyCode)\n || getNumberFormat(locale)[1] === getFormat(keyCode))) {\n return true;\n }\n return false;\n};\n\n/**\n *\n * @param {type} keyCode\n * @returns {Boolean}\n */\nisNumberKey = function(keyCode) {\n\n if ((keyCode >= 48 && keyCode <= 57) ||\n (keyCode >= 96 && keyCode <= 105)) {\n return true;\n }\n var keys = [8, 9, 13, 35, 36, 37, 39, 45, 46, 109, 144, 173, 189];\n if (keys.indexOf(keyCode) !== -1) {\n return true;\n }\n return false;\n};\n\n/**\n *\n * @param {type} keyCode\n * @returns {JSON@call;parse.numberFormatter.value|String}\n */\ngetFormat = function(keyCode) {\n\n var jsonString = '{\"numberFormatter\" : [{\"key\":\"32\", \"value\":\" \", \"description\":\"space\"}, {\"key\":\"188\", \"value\":\",\", \"description\":\"comma\"}, {\"key\":\"190\", \"value\":\".\", \"description\":\"dot\"}, {\"key\":\"110\", \"value\":\".\", \"description\":\"dot\"}]}';\n var jsonObject = JSON.parse(jsonString);\n for (var key in jsonObject.numberFormatter) {\n if (jsonObject.numberFormatter.hasOwnProperty(key)\n && keyCode === parseInt(jsonObject.numberFormatter[key].key)) {\n return jsonObject.numberFormatter[key].value;\n }\n }\n return '';\n};\n\n/**\n *\n * @type String\n */\nvar jsonString = '{\"shiftCharacterNumberMap\" : [{\"char\":\")\", \"number\":\"0\"}, {\"char\":\"!\", \"number\":\"1\"}, {\"char\":\"@\", \"number\":\"2\"}, {\"char\":\"#\", \"number\":\"3\"}, {\"char\":\"$\", \"number\":\"4\"}, {\"char\":\"%\", \"number\":\"5\"}, {\"char\":\"^\", \"number\":\"6\"}, {\"char\":\"&\", \"number\":\"7\"}, {\"char\":\"*\", \"number\":\"8\"}, {\"char\":\"(\", \"number\":\"9\"}]}';\n\n/**\n *\n * @param {type} value\n * @returns {JSON@call;parse.shiftCharacterNumberMap.number|String}\n */\ngetShiftCharSpecificNumber = function(value) {\n\n var jsonObject = JSON.parse(jsonString);\n for (var key in jsonObject.shiftCharacterNumberMap) {\n if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key)\n && value === jsonObject.shiftCharacterNumberMap[key].char) {\n return jsonObject.shiftCharacterNumberMap[key].number;\n }\n }\n return '';\n};\n\n/**\n *\n * @param {type} value\n * @returns {Boolean}\n */\nisShiftSpecificChar = function(value) {\n\n var jsonObject = JSON.parse(jsonString);\n for (var key in jsonObject.shiftCharacterNumberMap) {\n if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key)\n && value === jsonObject.shiftCharacterNumberMap[key].char) {\n return true;\n }\n }\n return false;\n};\n\n/**\n *\n * @param {type} element\n * @returns {undefined}\n */\nupdateField = function(element) {\n\n var value = element.value;\n\n for (var index = 0; index < value.length; index++) {\n if (!isShiftSpecificChar(value.charAt(index))) {\n continue;\n }\n element.value = value.replace(\n value.charAt(index),\n getShiftCharSpecificNumber(value.charAt(index)));\n }\n};\n\n/**\n *\n * @param {type} value\n * @param {type} element\n * @param {type} params\n */\njQuery.validator.addMethod('numberExceedsMaxLimit', function(value, element, params) {\n\n value = parseInt(parseNumber(value, params));\n if (value.toString().length > numericMaxLimit) {\n showErrorMessage(element.id, false, null);\n setFocus(element.id);\n return false;\n }\n return true;\n}, 'Exceeding the maximum limit of 13 digits. Example: 1234567890123.');\n\n/**\n *\n * @param {type} value\n * @param {type} element\n * @param {type} params\n */\njQuery.validator.addMethod('decimalExceedsMaxLimit', function(value, element, params) {\n\n value = parseFloat(parseDecimal(value, params)).toFixed(2);\n if (value.toString().substring(\n 0, value.toString().lastIndexOf('.')).length > numericMaxLimit\n || value.toString().length > decimalMaxLimit) {\n showErrorMessage(element.id, false, null);\n setFocus(element.id);\n return false;\n }\n return true;\n}, 'Exceeding the maximum limit of 16 digits. Example: 1234567890123.00.');\n\n/**\n * @param {type} id\n * @param {type} locale\n * @returns {boolean}\n */\nisNumberExceedMaxLimit = function(id, locale) {\n\n var value = parseInt(parseNumber(\n document.getElementById(id).value, locale));\n if (value.toString().length > numericMaxLimit) {\n setFocus(id);\n return true;\n }\n return false;\n};\n\n/**\n * @param {type} id\n * @param {type} locale\n * @returns {boolean}\n */\nisDecimalExceedsMaxLimit = function(id, locale) {\n\n var value = parseFloat(parseDecimal(\n document.getElementById(id).value, locale)).toFixed(2);\n if (value.toString().substring(\n 0, value.toString().lastIndexOf('.')).length > numericMaxLimit\n || value.toString().length > decimalMaxLimit) {\n setFocus(id);\n return true;\n }\n return false;\n};\n"
},
{
"answer_id": 58007996,
"author": "Murtaza Hussain",
"author_id": 4527878,
"author_profile": "https://Stackoverflow.com/users/4527878",
"pm_score": 3,
"selected": false,
"text": "var string = numeral(1000).format('0,0');\n// '1,000'\n"
},
{
"answer_id": 60877747,
"author": "Vinod Kumar",
"author_id": 3771354,
"author_profile": "https://Stackoverflow.com/users/3771354",
"pm_score": 5,
"selected": false,
"text": "\"250000\".replace(/(\\d)(?=(\\d{3})+(?!\\d))/g, '$1,');\n"
},
{
"answer_id": 64200888,
"author": "pgee70",
"author_id": 1490306,
"author_profile": "https://Stackoverflow.com/users/1490306",
"pm_score": 1,
"selected": false,
"text": "export const formatMoney = (\n amount,\n decimalCount = 2,\n decimal = '.',\n thousands = ',',\n currencySymbol = '$',\n) => {\n if (typeof Intl === 'object') {\n return new Intl.NumberFormat('en-AU', {\n style: 'currency',\n currency: 'AUD',\n }).format(amount);\n }\n // Fallback if Intl is not present.\n try {\n const negativeSign = amount < 0 ? '-' : '';\n const amountNumber = Math.abs(Number(amount) || 0).toFixed(decimalCount);\n const i = parseInt(amountNumber, 10).toString();\n const j = i.length > 3 ? i.length % 3 : 0;\n return (\n currencySymbol +\n negativeSign +\n (j ? i.substr(0, j) + thousands : '') +\n i.substr(j).replace(/(\\d{3})(?=\\d)/g, `$1${thousands}`) +\n (decimalCount\n ? decimal +\n Math.abs(amountNumber - i)\n .toFixed(decimalCount)\n .slice(2)\n : '')\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error(e);\n }\n return amount;\n};\n"
},
{
"answer_id": 68536579,
"author": "gadielkalleb",
"author_id": 11336223,
"author_profile": "https://Stackoverflow.com/users/11336223",
"pm_score": 5,
"selected": false,
"text": "const number = 1233445.5678\nconsole.log(new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(number));"
},
{
"answer_id": 74385955,
"author": "odionk",
"author_id": 13534081,
"author_profile": "https://Stackoverflow.com/users/13534081",
"pm_score": 0,
"selected": false,
"text": "function number_format(number, decimals = 0, dec_point = \".\",thousands_sep = \",\") {\n number = (number + '').replace(/[^0-9+\\-Ee.]/g, '');\n var n = !isFinite(+number) ? 0 : +number,\n prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),\n s = '',\n toFixedFix = function(n, prec)\n {\n var k = Math.pow(10, prec);\n return '' + (Math.round(n * k) / k).toFixed(prec);\n };\n // Fix for IE parseFloat(0.55).toFixed(0) = 0;\n s = (prec ? toFixedFix(n, prec) : '' + \n Math.round(n)).split('.');\n if (s[0].length > 3)\n {\n s[0] = s[0].replace(/\\B(?=(?:\\d{3})+(?!\\d))/g, \n thousands_sep);\n }\n if ((s[1] || '').length < prec)\n {\n s[1] = s[1] || '';\n s[1] += new Array(prec - s[1].length + 1).join('0');\n }\n return s.join(dec_point);\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
] |
149,057
|
<p>How can you remove all of the trailing whitespace of an entire project? Starting at a root directory, and removing the trailing whitespace from all files in all folders.</p>
<p>Also, I want to to be able to modify the file directly, and not just print everything to stdout.</p>
|
[
{
"answer_id": 149070,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 5,
"selected": false,
"text": "find dir -type f -exec sed -i 's/ *$//' '{}' ';' .git -not -iwholename '.git'"
},
{
"answer_id": 149081,
"author": "Sec",
"author_id": 20555,
"author_profile": "https://Stackoverflow.com/users/20555",
"pm_score": 5,
"selected": false,
"text": "find . -type f -print0 | xargs -0 perl -pi.bak -e 's/ +$//'\n find . -type f -print0 | xargs -0 perl -pi -e 's/ +$//'\n perl -pi -e 's/ +$//' **/*\n .git -not -iwholename '*.git*'"
},
{
"answer_id": 639043,
"author": "pojo",
"author_id": 70350,
"author_profile": "https://Stackoverflow.com/users/70350",
"pm_score": 4,
"selected": false,
"text": "find dir -type f -print0 | xargs -0 sed -i.bak -E \"s/[[:space:]]*$//\"\n find dir -not -path '.git' -iname '*.py'\n"
},
{
"answer_id": 1803902,
"author": "Jesper Rønn-Jensen",
"author_id": 109305,
"author_profile": "https://Stackoverflow.com/users/109305",
"pm_score": 3,
"selected": false,
"text": "sed -i '' 's/[[:space:]]*$//g' **/*.*\n"
},
{
"answer_id": 4198102,
"author": "odinho - Velmont",
"author_id": 179978,
"author_profile": "https://Stackoverflow.com/users/179978",
"pm_score": 3,
"selected": false,
"text": "find . -not \\( -name .svn -prune -o -name .git -prune \\) -type f \\\n -exec sed -i 's/[:space:]+$//' \\{} \\; \\\n -exec sed -i 's/\\r\\n$/\\n/' \\{} \\;\n -iname \"*.py\" -or -iname \"*.php\" -type f"
},
{
"answer_id": 5130044,
"author": "deepwell",
"author_id": 21473,
"author_profile": "https://Stackoverflow.com/users/21473",
"pm_score": 6,
"selected": false,
"text": "(export LANG=C LC_CTYPE=C\nfind . -not \\( -name .svn -prune -o -name .git -prune \\) -type f -print0 | perl -0ne 'print if -T' | xargs -0 sed -Ei 's/[[:blank:]]+$//'\n)\n L*"
},
{
"answer_id": 9639285,
"author": "ChicagoBob",
"author_id": 61614,
"author_profile": "https://Stackoverflow.com/users/61614",
"pm_score": 3,
"selected": false,
"text": "find . \\( -name *.rb -or -name *.html -or -name *.js -or -name *.coffee -or \\\n-name *.css -or -name *.scss -or -name *.erb -or -name *.yml -or -name *.ru \\) \\\n-print0 | xargs -0 sed -i '' -E \"s/[[:space:]]*$//\"\n"
},
{
"answer_id": 10120431,
"author": "l0b0",
"author_id": 96588,
"author_profile": "https://Stackoverflow.com/users/96588",
"pm_score": 5,
"selected": false,
"text": "text/ while IFS= read -r -d '' -u 9\ndo\n if [[ \"$(file -bs --mime-type -- \"$REPLY\")\" = text/* ]]\n then\n sed -i 's/[ \\t]\\+\\(\\r\\?\\)$/\\1/' -- \"$REPLY\"\n else\n echo \"Skipping $REPLY\" >&2\n fi\ndone 9< <(find . -type f -print0)\n -I git grep git grep -I --name-only -z -e '' | xargs -0 sed -i 's/[ \\t]\\+\\(\\r\\?\\)$/\\1/'\n"
},
{
"answer_id": 11861798,
"author": "yegor256",
"author_id": 187141,
"author_profile": "https://Stackoverflow.com/users/187141",
"pm_score": 1,
"selected": false,
"text": "find . -path ./vendor -prune -o \\\n \\( -name '*.java' -o -name '*.xml' -o -name '*.css' \\) \\\n -exec gsed -i -E 's/\\t/ /' \\{} \\; \\\n -exec gsed -i -E 's/[[:space:]]*$//' \\{} \\; \\\n -exec gsed -i -E 's/\\r\\n/\\n/' \\{} \\;\n \\n gsed"
},
{
"answer_id": 12508409,
"author": "Grant Murphy",
"author_id": 1312070,
"author_profile": "https://Stackoverflow.com/users/1312070",
"pm_score": 2,
"selected": false,
"text": "egrep -rl ' $' --include *.c * | xargs sed -i 's/\\s\\+$//g'\n"
},
{
"answer_id": 16246948,
"author": "jbbuckley",
"author_id": 884900,
"author_profile": "https://Stackoverflow.com/users/884900",
"pm_score": 4,
"selected": false,
"text": "ack --print0 -l '[ \\t]+$' | xargs -0 -n1 perl -pi -e 's/[ \\t]+$//'\n"
},
{
"answer_id": 23657918,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 3,
"selected": false,
"text": "ex $ ex +'bufdo!%s/\\s\\+$//e' -cxa **/*.*\n **/*.* shopt -s globstar .bash_profile # Strip trailing whitespaces.\n# Usage: trim *.*\n# See: https://stackoverflow.com/q/10711051/55075\ntrim() {\n ex +'bufdo!%s/\\s\\+$//e' -cxa $*\n}\n sed sed find remove_trail_spaces.sh #!/bin/sh\n# Script to remove trailing whitespace of all files recursively\n# See: https://stackoverflow.com/questions/149057/how-to-remove-trailing-whitespace-of-all-files-recursively\n\ncase \"$OSTYPE\" in\n darwin*) # OSX 10.5 Leopard, which does not use GNU sed or xargs.\n find . -type f -not -iwholename '*.git*' -print0 | xargs -0 sed -i .bak -E \"s/[[:space:]]*$//\"\n find . -type f -name \\*.bak -print0 | xargs -0 rm -v\n ;;\n *)\n find . -type f -not -iwholename '*.git*' -print0 | xargs -0 perl -pi -e 's/ +$//'\nesac\n .bak find . -type f -name \"*.java\" -exec perl -p -i -e \"s/[ \\t]$//g\" {} \\;\n"
},
{
"answer_id": 25131751,
"author": "grosser",
"author_id": 110333,
"author_profile": "https://Stackoverflow.com/users/110333",
"pm_score": 2,
"selected": false,
"text": "irb\nDir['lib/**/*.rb'].each{|f| x = File.read(f); File.write(f, x.gsub(/[ \\t]+$/,\"\")) }\n"
},
{
"answer_id": 40371757,
"author": "Ondra Žižka",
"author_id": 145989,
"author_profile": "https://Stackoverflow.com/users/145989",
"pm_score": 2,
"selected": false,
"text": "-E -r -i '' -i -i'' -i git config --global alias.check-whitespace \\\n'git diff-tree --check $(git hash-object -t tree /dev/null) HEAD'\n\ngit check-whitespace | grep trailing | cut -d: -f1 | uniq -u -z | xargs -0 sed --in-place -e 's/[ \\t]+$//'\n check-whitespace sed \\t [:space:]"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19718/"
] |
149,058
|
<p>There doesn't seem to be an accepted way of sending down a header parameter in non ascii format.</p>
<p>The header for file download usually looks like</p>
<p>Content-disposition: attachment; filename="theasciifilename.doc"</p>
<p>Except if you smash a utf8 encoded string in the filename parameter, Firefox will handle it fine, whereas IE will throw up.</p>
<p>There is a <a href="http://www.codeproject.com/KB/aspnet/NonUSASCII.aspx" rel="nofollow noreferrer">document on CodeProject that explains a method for encoding the filename.</a></p>
<p>This document encodes Bản Kiểm Kê.doc to B%e1%ba%a3n%20Ki%e1%bb%83m%20K%c3%aa.doc by hex encoding the bytes.</p>
<p>Problem #1: the first character in that string: ả has a value of ả -- encode that number in Hex and you get %a3%1e. How did this guy get %e1%ba%a3? (I'm obviously missing something simple here)</p>
<p>Problem #2: While IE acknowledges this encoding, Firefox doesn't! What to do?</p>
|
[
{
"answer_id": 149128,
"author": "Mr. Shiny and New 安宇",
"author_id": 7867,
"author_profile": "https://Stackoverflow.com/users/7867",
"pm_score": 3,
"selected": true,
"text": "0xE1 0xBA 0xA3"
},
{
"answer_id": 149529,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 0,
"selected": false,
"text": "1. If browser is IE URL encode filename\n2. Generate Content-disposition header\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/245/"
] |
149,073
|
<p>I want to see the stack trace in any function of my code, so i made somthing like this to call it and print the stack trace:</p>
<pre><code>public function PrintStackTrace() {
try {
throw new Error('StackTrace');
} catch (e:Error) {
trace(e.getStackTrace());
}
}
</code></pre>
<p>I like to know if there are other way to do this. In some place, the Error class creates the stack trace, but maybe it didn't do it with ActionScript 3.0 so maybe it's not posible, but i want to know.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 149188,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 7,
"selected": true,
"text": "var tempError:Error = new Error();\nvar stackTrace:String = tempError.getStackTrace();\n"
},
{
"answer_id": 20659235,
"author": "gaurav_gupta",
"author_id": 1157936,
"author_profile": "https://Stackoverflow.com/users/1157936",
"pm_score": 1,
"selected": false,
"text": "var tempError:Error = new Error();\nvar stackTrace:String = tempError.getStackTrace();\n stackTrace uncaughtexception"
},
{
"answer_id": 25493160,
"author": "BlueRaja - Danny Pflughoeft",
"author_id": 238419,
"author_profile": "https://Stackoverflow.com/users/238419",
"pm_score": 1,
"selected": false,
"text": "Flash Builder --> Project properties --> ActionScript Compiler"
},
{
"answer_id": 36290419,
"author": "OMA",
"author_id": 732669,
"author_profile": "https://Stackoverflow.com/users/732669",
"pm_score": 2,
"selected": false,
"text": "public static function getStackTrace() : String\n{\n var aStackTrace : Array = new Error().getStackTrace().split(\"\\n\");\n aStackTrace.shift();\n aStackTrace.shift();\n return \"Stack trace: \\n\" + aStackTrace.join(\"\\n\");\n}\n"
},
{
"answer_id": 38303128,
"author": "Andrei Tofan",
"author_id": 2464151,
"author_profile": "https://Stackoverflow.com/users/2464151",
"pm_score": 0,
"selected": false,
"text": "getStackTrace null -compiler.verbose-stacktraces=true"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601/"
] |
149,078
|
<p>Suppose I have a database table with two fields, "foo" and "bar". Neither of them are unique, but each of them are indexed. However, rather than being indexed together, they each have a separate index.</p>
<p>Now suppose I perform a query such as <code>SELECT * FROM sometable WHERE foo='hello' AND bar='world';</code> My table a huge number of rows for which foo is 'hello' and a small number of rows for which bar is 'world'.</p>
<p>So the most efficient thing for the database server to do under the hood is use the bar index to find all fields where bar is 'world', then return only those rows for which foo is 'hello'. This is <code>O(n)</code> where n is the number of rows where bar is 'world'.</p>
<p>However, I imagine it's possible that the process would happen in reverse, where the fo index was used and the results searched. This would be <code>O(m)</code> where m is the number of rows where foo is 'hello'.</p>
<p>So is Oracle smart enough to search efficiently here? What about other databases? Or is there some way I can tell it in my query to search in the proper order? Perhaps by putting <code>bar='world'</code> first in the <code>WHERE</code> clause?</p>
|
[
{
"answer_id": 149104,
"author": "Georgi",
"author_id": 13209,
"author_profile": "https://Stackoverflow.com/users/13209",
"pm_score": 2,
"selected": false,
"text": "CREATE INDEX IX_BAR_AND_FOO on sometable(bar,foo);\n"
},
{
"answer_id": 149168,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 5,
"selected": true,
"text": "explain plan for\nSELECT *\nFROM sometable\nWHERE foo='hello' AND bar='world'\n/\nselect * from table(dbms_xplan.display)\n/\n explain plan for\nSELECT /*+ dynamic_sampling(4) */\n *\nFROM sometable\nWHERE foo='hello' AND bar='world'\n/\nselect * from table(dbms_xplan.display)\n/\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
] |
149,092
|
<p>I have backups of files archived in optical media (CDs and DVDs). These all have par2 recovery files, stored on separate media. Even in cases where there are no par2 files, minor errors when reading on one optical drive can be read fine on another drive.</p>
<p>The thing is, when reading faulty media, the read time is very, very long, because devices tend to retry multiple times.</p>
<p>The question is: how can I control the number of retries (ie set to no retries or only one try)? Some system call? A library I can download? Do I have to work on the SCSI layer?</p>
<p>The question is mainly about Linux, but any Win32 pointers will be more than welcome too.</p>
|
[
{
"answer_id": 150102,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 1,
"selected": false,
"text": "hdparm"
},
{
"answer_id": 150252,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "sdparm sudo sdparm --set=RRC=0 /dev/sr0\n /dev/sr0"
},
{
"answer_id": 552596,
"author": "derobert",
"author_id": 27727,
"author_profile": "https://Stackoverflow.com/users/27727",
"pm_score": 4,
"selected": true,
"text": "man readom -noerror\n Do not abort if the high level error checking in readom found an\n uncorrectable error in the data stream.\n\n -nocorr\n Switch the drive into a mode where it ignores read errors in\n data sectors that are a result of uncorrectable ECC/EDC errors\n before reading. If readom completes, the error recovery mode of\n the drive is switched back to the remembered old mode.\n ...\n\n retries=#\n Set the retry count for high level retries in readom to #. The\n default is to do 128 retries which may be too much if you like\n to read a CD with many unreadable sectors.\n"
},
{
"answer_id": 556871,
"author": "motobói",
"author_id": 25612,
"author_profile": "https://Stackoverflow.com/users/25612",
"pm_score": 3,
"selected": false,
"text": "dd_rhelp /dev/cdrecorder /home/myself/DVD.img\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6899/"
] |
149,102
|
<p>How can I capture the event in Excel when a user clicks on a cell. I want to be able to use this event to trigger some code to count how many times the user clicks on several different cells in a column.</p>
|
[
{
"answer_id": 149121,
"author": "Robert S.",
"author_id": 7565,
"author_profile": "https://Stackoverflow.com/users/7565",
"pm_score": 3,
"selected": true,
"text": "Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)\n If Not Intersect(Target, Range(\"SomeNamedRange\")) Is Nothing Then\n 'Your counting code \n End If\nEnd Sub\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22376/"
] |
149,132
|
<p>I'm not sure if this is something I should do in T-SQL or not, and I'm pretty sure using the word 'iterate' was wrong in this context, since you should never iterate anything in sql. It should be a set based operation, correct? Anyway, here's the scenario:</p>
<p>I have a stored proc that returns many uniqueidentifiers (single column results). These ids are the primary keys of records in a another table. I need to set a flag on all the corresponding records in that table.</p>
<p>How do I do this without the use of cursors? Should be an easy one for you sql gurus!</p>
|
[
{
"answer_id": 149152,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 5,
"selected": true,
"text": "CREATE TABLE #t (uniqueid int)\nINSERT INTO #t EXEC p_YourStoredProc\n\nUPDATE TargetTable \nSET a.FlagColumn = 1\nFROM TargetTable a JOIN #t b \n ON a.uniqueid = b.uniqueid\n\nDROP TABLE #t\n"
},
{
"answer_id": 149160,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "INSERT INTO #WorkTable\nEXEC usp_WorkResults\n\nUPDATE DataTable\n SET Flag = Whatever\nFROM DataTable\nINNER JOIN #WorkTable\n ON DataTable.Ket = #WorkTable.Key\n"
},
{
"answer_id": 149179,
"author": "technophile",
"author_id": 23029,
"author_profile": "https://Stackoverflow.com/users/23029",
"pm_score": -1,
"selected": false,
"text": "DECLARE @MyTable TABLE (\n Column1 uniqueidentifer,\n ...,\n Checked bit\n)\n\nINSERT INTO @MyTable\nSELECT [...], 0 FROM MyTable WHERE [...]\n\nDECLARE @Continue bit\nSET @Continue = 1\nWHILE (@Continue)\nBEGIN\n SELECT @var1 = Column1,\n @var2 = Column2,\n ...\n FROM @MyTable\n WHERE Checked = 1\n\n IF @var1 IS NULL\n SET @Continue = 0\n ELSE\n BEGIN\n\n ...\n\n UPDATE @MyTable SET Checked = 1 WHERE Column1 = @var1\n END\nEND\n"
},
{
"answer_id": 151567,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 2,
"selected": false,
"text": "CREATE FUNCTION dbo.udfGetUniqueIDs\n()\nRETURNS TABLE \nAS\nRETURN \n(\n SELECT uniqueid FROM dbo.SomeWhere\n)\n\nGO\n\nUPDATE dbo.TargetTable \nSET a.FlagColumn = 1\nFROM dbo.TargetTable a INNER JOIN dbo.udfGetUniqueIDs() b \n ON a.uniqueid = b.uniqueid\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
] |
149,153
|
<p>I'm trying to create a ImageIcon from a animated gif stored in a jar file.</p>
<pre><code>ImageIcon imageIcon = new ImageIcon(ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream("animated.gif")));
</code></pre>
<p>The image loads, but only the first frame of the animated gif. The animation does not play. </p>
<p>If I load the animated gif from a file on the filesystem, everything works as expected. The animation plays through all the of frames. So this works:</p>
<pre><code>ImageIcon imageIcon = new ImageIcon("/path/on/filesystem/animated.gif");
</code></pre>
<p>How can I load an animated gif into an ImageIcon from a jar file?</p>
<p>EDIT: Here is a complete test case, why doesn't this display the animation?</p>
<pre><code>import javax.imageio.ImageIO;
import javax.swing.*;
public class AnimationTest extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
AnimationTest test = new AnimationTest();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setVisible(true);
}
});
}
public AnimationTest() {
super();
try {
JLabel label = new JLabel();
ImageIcon imageIcon = new ImageIcon(ImageIO.read(AnimationTest.class.getClassLoader().getResourceAsStream("animated.gif")));
label.setIcon(imageIcon);
imageIcon.setImageObserver(label);
add(label);
pack();
} catch (Exception e) {
e.printStackTrace();
}
}
}
</code></pre>
|
[
{
"answer_id": 5444422,
"author": "Andrew Thompson",
"author_id": 418556,
"author_profile": "https://Stackoverflow.com/users/418556",
"pm_score": 2,
"selected": false,
"text": "import javax.swing.*;\nimport java.net.URL;\n\nclass AnimatedGifInLabel {\n\n public static void main(String[] args) throws Exception {\n final URL url = new URL(\"http://i.stack.imgur.com/OtTIY.gif\");\n Runnable r = new Runnable() {\n public void run() {\n ImageIcon ii = new ImageIcon(url);\n JLabel label = new JLabel(ii);\n JOptionPane.showMessageDialog(null, label);\n }\n };\n SwingUtilities.invokeLater(r);\n }\n}\n"
},
{
"answer_id": 6504520,
"author": "Penkov Vladimir",
"author_id": 555830,
"author_profile": "https://Stackoverflow.com/users/555830",
"pm_score": 4,
"selected": true,
"text": "InputStream in = ...;\nImage image = Toolkit.getDefaultToolkit().createImage(org.apache.commons.io.IOUtils.toByteArray(in));\n"
},
{
"answer_id": 15166546,
"author": "Paulo Pedroso",
"author_id": 1474815,
"author_profile": "https://Stackoverflow.com/users/1474815",
"pm_score": 1,
"selected": false,
"text": "private JPanel loadingPanel() {\n JPanel panel = new JPanel();\n BoxLayout layoutMgr = new BoxLayout(panel, BoxLayout.PAGE_AXIS);\n panel.setLayout(layoutMgr);\n\n ClassLoader cldr = this.getClass().getClassLoader();\n java.net.URL imageURL = cldr.getResource(\"img/spinner.gif\");\n ImageIcon imageIcon = new ImageIcon(imageURL);\n JLabel iconLabel = new JLabel();\n iconLabel.setIcon(imageIcon);\n imageIcon.setImageObserver(iconLabel);\n\n JLabel label = new JLabel(\"Loading...\");\n panel.add(iconLabel);\n panel.add(label);\n return panel;\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/739/"
] |
149,191
|
<p>I am seeing some rather weird behavior with PowerShell, it looks like custom functions might need a "parenthesis wrapper" to evaluate as you might expect them. Given a simple PowerShell function:</p>
<pre><code>function Return-True { return $true }
</code></pre>
<p>and then some sample code to invoke it:</p>
<pre><code>PS C:\> Return-True
True
PS C:\> Return-True -eq $false
True
PS C:\> (Return-True) -eq $false
False
</code></pre>
<p>Ideas? Comments? </p>
|
[
{
"answer_id": 149373,
"author": "hurcane",
"author_id": 21363,
"author_profile": "https://Stackoverflow.com/users/21363",
"pm_score": 3,
"selected": false,
"text": "PS C:\\> function Return-True { return \"True string\" }\nPS C:\\> Return-True\nTrue string\nPS C:\\> Return-True -eq \"False string\"\nTrue string\nPS C:\\> (Return-True) -eq \"False string\"\nFalse\n"
},
{
"answer_id": 149376,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 6,
"selected": true,
"text": "Return-True Return-True PS > function Return-True { \"The arguments are: $args\"; return $true }\nPS > Return-True -eq $false\nThe arguments are: -eq False\nTrue\n Return-True PS > Return-True -eq $false\nTrue\nPS > Return-True -ne $false\nTrue\nPS > Return-True -eq $true\nTrue\nPS > Return-True -ne $true\nTrue\n (Return-True)"
},
{
"answer_id": 957587,
"author": "mrwaim",
"author_id": 97909,
"author_profile": "https://Stackoverflow.com/users/97909",
"pm_score": 3,
"selected": false,
"text": "function Return-True\n{\n [CmdletBinding()]\n param()\n return $true\n}\nReturn-True -eq $false\n\nReturn-True -eq $false\nReturn-True : A parameter cannot be found that matches parameter name 'eq'.\nAt line:7 char:16\n+ Return-True -eq <<<< $false\n + CategoryInfo : InvalidArgument: (:) [Return-True], ParameterBindingException\n + FullyQualifiedErrorId : NamedParameterNotFound,Return-True\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/243/"
] |
149,198
|
<p>I use Tortoise SVN usuallly, but I have been looking into Mercurial since it is a distributed revision control system. </p>
<p>What I am looking for, in both systems, is a tool that let me pick only parts of a file and commit them. If I want to do this now, I have to copy to a temp version of the file and keep only the changes I want to commit in the current version, and then copy the temp version to the current version again after committing. It's just such a hassle and the program should be able to do this for me.</p>
<p>I heard Git supports this, please let me know if this is correct.</p>
|
[
{
"answer_id": 149270,
"author": "Nicholas Riley",
"author_id": 6372,
"author_profile": "https://Stackoverflow.com/users/6372",
"pm_score": 6,
"selected": true,
"text": "% hg record\ndiff --git a/prelim.tex b/prelim.tex\n2 hunks, 4 lines changed\nexamine changes to 'prelim.tex'? [Ynsfdaq?] \n@@ -12,7 +12,7 @@\n \\setmonofont[Scale=0.88]{Consolas}\n % missing from xunicode.sty\n \\DeclareUTFcomposite[\\UTFencname]{x00ED}{\\'}{\\i}\n-\\else\n+\\else foo\n \\usepackage[pdftex]{graphicx}\n \\fi\n\nrecord this change to 'prelim.tex'? [Ynsfdaq?] \n@@ -1281,3 +1281,5 @@\n %% Local variables:\n %% mode: latex\n %% End:\n+\n+foo\n\\ No newline at end of file\nrecord this change to 'prelim.tex'? [Ynsfdaq?] n\nWaiting for Emacs...\n % hg di\ndiff --git a/prelim.tex b/prelim.tex\n--- a/prelim.tex\n+++ b/prelim.tex\n@@ -1281,3 +1281,5 @@\n %% Local variables:\n %% mode: latex\n %% End:\n+\n+foo\n\\ No newline at end of file\n"
},
{
"answer_id": 151784,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 4,
"selected": false,
"text": "git add -p --patch git add -i git add"
},
{
"answer_id": 46101985,
"author": "Oly",
"author_id": 5181199,
"author_profile": "https://Stackoverflow.com/users/5181199",
"pm_score": 2,
"selected": false,
"text": "--interactive -i commit > hg commit -i\n --patch --interactive git add git commit"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6752/"
] |
149,200
|
<p>I have an application that uses Forms Authentication to authenticate one type of user. There is a section in this application that needs to be authenticated for another type of user using a different table in the database. The problem happens if the second type of user's session times out, she is taken to the login page defined in the Forms Authentication section of the main Web.Config instead of the login page for the second type of user. I am looking for solutions to this problem. One idea is to create an application in IIS for the section and create a Web.Config for the folder and add another Forms Authentication section. In my experiments, it seems this doesn't work. Am I missing something obvious? Any insights? </p>
|
[
{
"answer_id": 149255,
"author": "Ian Jacobs",
"author_id": 22818,
"author_profile": "https://Stackoverflow.com/users/22818",
"pm_score": 1,
"selected": false,
"text": "<location>...</location> \n"
},
{
"answer_id": 150169,
"author": "Ty.",
"author_id": 8873,
"author_profile": "https://Stackoverflow.com/users/8873",
"pm_score": 0,
"selected": false,
"text": "<Location>"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21160/"
] |
149,206
|
<p>I have a XML response from an HTTPService call with the e4x result format.</p>
<pre>
<code>
<?xml version="1.0" encoding="utf-8"?>
<Validation Error="Invalid Username/Password Combination" />
</code>
</pre>
<p>I have tried:</p>
<pre>
<code>
private function callback(event:ResultEvent):void {
if(event.result..@Error) {
// error attr present
}
else {
// error attr not present
}
}
</code>
</pre>
<p>This does not seem to work (it always thinks that the error attribute exits) what is the best way to do this? thanks.</p>
<p><b>EDIT:</b> I have also tried to compare the attribute to null and an empty string without such success...</p>
|
[
{
"answer_id": 149291,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 1,
"selected": false,
"text": "\nprivate function callback(event:ResultEvent):void {\n if(event.result.attribute(\"Error\").length()) {\n // error attr present\n }\n else {\n // error attr not present\n }\n}\n"
},
{
"answer_id": 149316,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 2,
"selected": false,
"text": "event.result XML var error:String = event.result.@Error;\nif (error != \"\")\n // error\nelse\n // no error\n Error if (event.result.hasOwnProperty(\"@Error\"))\n // error\nelse\n // no error\n"
},
{
"answer_id": 149794,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 4,
"selected": false,
"text": "event.result.attribute(\"Error\").length() > 0\n attribute"
},
{
"answer_id": 150179,
"author": "Christophe Herreman",
"author_id": 17255,
"author_profile": "https://Stackoverflow.com/users/17255",
"pm_score": 2,
"selected": false,
"text": "if (undefined == event.result.@Error)\n if (undefined == event.result.@[attributeName])\n"
},
{
"answer_id": 627164,
"author": "Paul Mignard",
"author_id": 3435,
"author_profile": "https://Stackoverflow.com/users/3435",
"pm_score": 3,
"selected": false,
"text": "if(\"@property\" in node){//do something}\n"
},
{
"answer_id": 4019282,
"author": "Rihards",
"author_id": 374476,
"author_profile": "https://Stackoverflow.com/users/374476",
"pm_score": 0,
"selected": false,
"text": "if(event.result.@error[0]){\n //exists \n}\n"
},
{
"answer_id": 17086830,
"author": "1.21 gigawatts",
"author_id": 441016,
"author_profile": "https://Stackoverflow.com/users/441016",
"pm_score": 2,
"selected": false,
"text": "if (\"@style\" in item) // do something\n attribute var attributeName:String = \"style\";\nvar attributeWithAtSign:String = \"@\" + attributeName;\nvar item:XML = <item style=\"value\"/>;\nvar itemNoAttribute:XML = <item />;\n\nif (attributeWithAtSign in itemNoAttribute) {\n trace(\"should not be here if attribute is not on the xml\");\n}\nelse {\n trace(attributeName + \" not found in \" + itemNoAttribute);\n}\n\nif (attributeWithAtSign in item) {\n item.attribute(attributeName)[0] = \"a new value\";\n}\n 807 item.hasOwnProperty(\"@style\")\n824 \"@style\" in item\n1756 item.@style[0]\n2166 (undefined != item.@[\"style\"])\n2431 (undefined != item[\"@style\"])\n3050 XML(item).attribute(\"style\").length()>0\n var item:XML = <item value=\"value\"/>;\nvar attExists:Boolean;\nvar million:int = 1000000;\nvar time:int = getTimer();\n\nfor (var j:int;j<million;j++) {\n attExists = XML(item).attribute(\"style\").length()>0;\n attExists = XML(item).attribute(\"value\").length()>0;\n}\n\nvar test1:int = getTimer() - time; // 3242 3050 3759 3075\n\ntime = getTimer();\n\nfor (var j:int=0;j<million;j++) {\n attExists = \"@style\" in item;\n attExists = \"@value\" in item;\n}\n\nvar test2:int = getTimer() - time; // 1089 852 991 824\n\ntime = getTimer();\n\nfor (var j:int=0;j<million;j++) {\n attExists = (undefined != item.@[\"style\"]);\n attExists = (undefined != item.@[\"value\"]);\n}\n\nvar test3:int = getTimer() - time; // 2371 2413 2790 2166\n\ntime = getTimer();\n\nfor (var j:int=0;j<million;j++) {\n attExists = (undefined != item[\"@style\"]);\n attExists = (undefined != item[\"@value\"]);\n}\n\nvar test3_1:int = getTimer() - time; // 2662 3287 2941 2431\n\ntime = getTimer();\n\nfor (var j:int=0;j<million;j++) {\n attExists = item.hasOwnProperty(\"@style\");\n attExists = item.hasOwnProperty(\"@value\");\n}\n\nvar test4:int = getTimer() - time; // 900 946 960 807\n\ntime = getTimer();\n\nfor (var j:int=0;j<million;j++) {\n attExists = item.@style[0];\n attExists = item.@value[0];\n}\n\nvar test5:int = getTimer() - time; // 1838 1756 1756 1775\n"
},
{
"answer_id": 71918664,
"author": "lojolis",
"author_id": 17728701,
"author_profile": "https://Stackoverflow.com/users/17728701",
"pm_score": 0,
"selected": false,
"text": "if (undefined == event.result.@[attributeName]);\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
149,213
|
<p>Does anybody know what hypothetical indexes are used for in sql server 2000? I have a table with 15+ such indexes, but have no idea what they were created for. Can they slow down deletes/inserts?</p>
|
[
{
"answer_id": 149224,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 1,
"selected": false,
"text": "SELECT *\nFROM sys.indexes\nWHERE is_hypothetical = 1\n"
},
{
"answer_id": 56820837,
"author": "Lukasz Szozda",
"author_id": 5070879,
"author_profile": "https://Stackoverflow.com/users/5070879",
"pm_score": 0,
"selected": false,
"text": "is_hypothetical bit \n\n1 = Index is hypothetical and cannot be used directly as a data access path. \n Hypothetical indexes hold column-level statistics.\n\n0 = Index is not hypothetical.\n WITH STATISTICS_ONLY CREATE TABLE tab(id INT PRIMARY KEY, i INT);\n\nCREATE INDEX MyHypIndex ON tab(i) WITH STATISTICS_ONLY = 0;\n/* 0 - withoud statistics -1 - generate statistics */\n\nSELECT name, is_hypothetical\nFROM sys.indexes\nWHERE object_id = OBJECT_ID('tab');\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12772/"
] |
149,233
|
<p>I have 7-8 xml files. Each one is approximately 50 MB in size. What is the best way to merge files programmatically in C# without getting System.OutOfMemory Exception? So far I have tried reading each file in a StringBuilder and than putting it in an array of string builder but I still get system.outofmemoery exception. Any help??
Thank you,
-Nimesh</p>
|
[
{
"answer_id": 149264,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 0,
"selected": false,
"text": "<items>\n <item id=\"1\">\n <name>Widget</name>\n </item>\n <item id=\"2\">\n <name>Widget 2</name>\n </item>\n</items>\n <items>\n <item id=\"3\">\n <name>Widget</name>\n </item>\n <item id=\"4\">\n <name>Widget 2</name>\n </item>\n</items>\n <items>\n <item id=\"1\">\n <name>Widget</name>\n </item>\n <item id=\"2\">\n <name>Widget 2</name>\n </item>\n</items>\n<items>\n <item id=\"3\">\n <name>Widget</name>\n </item>\n <item id=\"4\">\n <name>Widget 2</name>\n </item>\n</items>\n <items>\n <item id=\"1\">\n <name>Widget</name>\n </item>\n <item id=\"2\">\n <name>Widget 2</name>\n </item>\n <item id=\"3\">\n <name>Widget</name>\n </item>\n <item id=\"4\">\n <name>Widget 2</name>\n </item>\n</items>\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
149,236
|
<p>I'm slowly getting back into PHP, and now I run into a problem, I want to install some web software on our host and I need to have either the latest Zend (which they don't have) or IonCube on the server and IonCube requires enable_dl to be on in the php.ini. Now a colleague of mine thinks I can update this via an .htaccess file on the server. So I created a s.htaccess on my machine as Windows doesn't like emptiness before the file extension. So I added the line php_flag enable_dl On to the file uploaded it and renamed the file to just .htaccess on the server. When I refresh the file is gone, when I keep it as s.htaccess it's fine but my php info still shows it as Off.</p>
<p>What n00b mistake am I making?</p>
|
[
{
"answer_id": 149264,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 0,
"selected": false,
"text": "<items>\n <item id=\"1\">\n <name>Widget</name>\n </item>\n <item id=\"2\">\n <name>Widget 2</name>\n </item>\n</items>\n <items>\n <item id=\"3\">\n <name>Widget</name>\n </item>\n <item id=\"4\">\n <name>Widget 2</name>\n </item>\n</items>\n <items>\n <item id=\"1\">\n <name>Widget</name>\n </item>\n <item id=\"2\">\n <name>Widget 2</name>\n </item>\n</items>\n<items>\n <item id=\"3\">\n <name>Widget</name>\n </item>\n <item id=\"4\">\n <name>Widget 2</name>\n </item>\n</items>\n <items>\n <item id=\"1\">\n <name>Widget</name>\n </item>\n <item id=\"2\">\n <name>Widget 2</name>\n </item>\n <item id=\"3\">\n <name>Widget</name>\n </item>\n <item id=\"4\">\n <name>Widget 2</name>\n </item>\n</items>\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841427/"
] |
149,262
|
<p>What delphi function asserts that an object is not nil?</p>
|
[
{
"answer_id": 149296,
"author": "Roman Ganz",
"author_id": 17981,
"author_profile": "https://Stackoverflow.com/users/17981",
"pm_score": 3,
"selected": false,
"text": "Assert(Assigned(MyObject));"
},
{
"answer_id": 149351,
"author": "Mihai Limbășan",
"author_id": 14444,
"author_profile": "https://Stackoverflow.com/users/14444",
"pm_score": 5,
"selected": true,
"text": "Assert() Assigned(obj) true nil Assert(obj <> nil) Assigned() Assigned()"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765/"
] |
149,268
|
<p>Since I have started using this site, I keep hearing about the Boost library. I am wondering what are some of the major benefits of the Boost library (hence why should I use it) and how portable is the Boost library?</p>
|
[
{
"answer_id": 149285,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 4,
"selected": false,
"text": "int iResult = 0;\ntry\n{\n iResult = lexical_cast<int>(\"4\");\n}\ncatch(bad_lexical_cast &)\n{\n cout << \"Unable to cast string to int\";\n}\n using namespace boost::gregorian;\ndate weekstart(2002,Feb,1);\ndate thursday_next = next_weekday(weekstart, Thursday); // following Thursday\n // A grammar in C++ for equations\ngroup = '(' >> expression >> ')';\nfactor = integer | group;\nterm = factor >> *(('*' >> factor) | ('/' >> factor));\nexpression = term >> *(('+' >> term) | ('-' >> term));\n"
},
{
"answer_id": 149305,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 7,
"selected": true,
"text": "<boost-install-path>/boost/tr1/tr1\n"
},
{
"answer_id": 275293,
"author": "Michel",
"author_id": 31122,
"author_profile": "https://Stackoverflow.com/users/31122",
"pm_score": 2,
"selected": false,
"text": "shared_ptr weak_ptr BOOST_STATIC_ASSERT"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20229/"
] |
149,307
|
<p>How can I run background tasks on App Engine?</p>
|
[
{
"answer_id": 35063902,
"author": "phucat",
"author_id": 755410,
"author_profile": "https://Stackoverflow.com/users/755410",
"pm_score": 1,
"selected": false,
"text": "from google.appengine.ext import deferred\n\ndef do_something_expensive(a, b, c=None):\n logging.info(\"Doing something expensive!\")\n # Do your work here\n\n# Somewhere else\ndeferred.defer(do_something_expensive, \"Hello, world!\", 42, c=True)\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
149,311
|
<p>When adding an EditItemTemplate of some complexity (mulitple fields in one template), and then parsing the controls from the RowUpdating event, the controls that were manually entered by the user have no values. My guess is there is something going on with when the data is bound, but I've had instances where simply adding and attribute to a control in codebehind started the behavior and removing that code made the code work. As a work-around, I can Request(controlname.UniqueId) to get it's value, but that is rather a hack.</p>
<p><strong>Edit</strong>
When I access the value like so</p>
<pre><code>TextBox txtValue = gvwSettings.SelectedRow.FindControl("txtValue") as TextBox;
</code></pre>
<p>the text box is found, but the .Text is not the user input.</p>
|
[
{
"answer_id": 149392,
"author": "Elijah Manor",
"author_id": 4481,
"author_profile": "https://Stackoverflow.com/users/4481",
"pm_score": 0,
"selected": false,
"text": "TextBox txtValue = gvwSettings.SelectedRow.FindControl(\"txtValue\") as TextBox;\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2017/"
] |
149,324
|
<p>Is there a way set flags on a per-file basis with automake?<br>
In particular, if I have a c++ project and want to compile with -WAll all the files except one for which I want to disable a particular warning, what could I do?</p>
<p>I tried something like:</p>
<pre><code>CXXFLAGS = -WAll ...
bin_PROGRAMS = test
test_SOURCES = main.cpp utility.cpp
utility_o_CXXFLAGS = $(CXXFLAGS) -Wno-unused-value
</code></pre>
<p>but it didn't work.</p>
<p>EDITED: removed reference to automake manual, which was actually misleading (thanks to Douglas Leeder).</p>
|
[
{
"answer_id": 149642,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 2,
"selected": false,
"text": "gnu\n warnings related to the GNU Coding Standards (see Top).\nobsolete\n obsolete features or constructions\noverride\n user redefinitions of Automake rules or variables\nportability\n portability issues (e.g., use of make features that are known to be not portable)\nsyntax\n weird syntax, unused variables, typos\nunsupported\n unsupported or incomplete features\nall\n all the warnings\nnone\n turn off all the warnings\nerror\n treat warnings as errors \n binaryname_CXXFLAGS\n"
},
{
"answer_id": 201418,
"author": "adl",
"author_id": 27835,
"author_profile": "https://Stackoverflow.com/users/27835",
"pm_score": 4,
"selected": true,
"text": "CXXFLAGS = -Wall ...\nbin_PROGRAMS = test\ntest_SOURCES = main.cpp\ntest_LDADD = libutility.a\nnoinst_LIBRARIES = libutility.a\nlibutility_a_SOURCES = utility.cpp\nlibutility_a_CXXFLAGS = $(CXXFLAGS) -Wno-unused-value\n"
},
{
"answer_id": 12371346,
"author": "Andrey Starodubtsev",
"author_id": 814297,
"author_profile": "https://Stackoverflow.com/users/814297",
"pm_score": 4,
"selected": false,
"text": "automake make Makefile.am utility.$(OBJEXT) : CXXFLAGS += -Wno-unused-value\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15622/"
] |
149,337
|
<p>Is it possible to create a .NET equivalent to the following code?</p>
<pre><code><?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;
} else {
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>
</code></pre>
<p>I would like to be able to define a static user/password in the web.config as well. This is very easy to do in PHP, haven't seen anything explaining how to do this in MSDN.</p>
<hr>
<p>All I want is this:</p>
<p><img src="https://i.stack.imgur.com/IJE1b.png" alt="https://i.stack.imgur.com/IJE1b.png"></p>
|
[
{
"answer_id": 149390,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 0,
"selected": false,
"text": "if(SecurityHelper.LoginUser(txtUsername.Text, txtPassword.Text))\n{\n FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);\n}\n"
},
{
"answer_id": 149440,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 0,
"selected": false,
"text": "System.Security.Principal.WindowsIdentity.GetCurrent().IsAuthenticated\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/795/"
] |
149,375
|
<p>Is there any way to do this in the Powerbuilder properties window for a datawindow's textbox?</p>
|
[
{
"answer_id": 3128575,
"author": "Matt",
"author_id": 377533,
"author_profile": "https://Stackoverflow.com/users/377533",
"pm_score": 1,
"selected": false,
"text": "® ls_key = '®"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12646/"
] |
149,379
|
<p>I want to create Code39 encoded barcodes from my application. </p>
<p>I know I can use a font for this, but I'd prefer not to as I'd have to register the font on the server and I've had some pretty bad experiences with that.</p>
<p><em>An example of what I've produced after asking this question is in the answers</em></p>
|
[
{
"answer_id": 156784,
"author": "sebastiaan",
"author_id": 5018,
"author_profile": "https://Stackoverflow.com/users/5018",
"pm_score": 5,
"selected": true,
"text": "Option Explicit On\nOption Strict On\n\nImports System.Drawing\nImports System.Drawing.Imaging\nImports System.Drawing.Bitmap\nImports System.Drawing.Graphics\nImports System.IO\n\nPartial Public Class Barcode\n Inherits System.Web.UI.Page\n 'Sebastiaan Janssen - 20081001 - TINT-30584\n 'Most of the code is based on this example: \n 'http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/04/25/writing-code-39-barcodes-with-javascript.aspx-generation.aspx\n 'With a bit of this thrown in:\n 'http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/03/24/code-39-barcode\n\n Private _encoding As Hashtable = New Hashtable\n Private Const _wideBarWidth As Short = 8\n Private Const _narrowBarWidth As Short = 2\n Private Const _barHeight As Short = 100\n\n Sub BarcodeCode39()\n _encoding.Add(\"*\", \"bWbwBwBwb\")\n _encoding.Add(\"-\", \"bWbwbwBwB\")\n _encoding.Add(\"$\", \"bWbWbWbwb\")\n _encoding.Add(\"%\", \"bwbWbWbWb\")\n _encoding.Add(\" \", \"bWBwbwBwb\")\n _encoding.Add(\".\", \"BWbwbwBwb\")\n _encoding.Add(\"/\", \"bWbWbwbWb\")\n _encoding.Add(\"+\", \"bWbwbWbWb\")\n _encoding.Add(\"0\", \"bwbWBwBwb\")\n _encoding.Add(\"1\", \"BwbWbwbwB\")\n _encoding.Add(\"2\", \"bwBWbwbwB\")\n _encoding.Add(\"3\", \"BwBWbwbwb\")\n _encoding.Add(\"4\", \"bwbWBwbwB\")\n _encoding.Add(\"5\", \"BwbWBwbwb\")\n _encoding.Add(\"6\", \"bwBWBwbwb\")\n _encoding.Add(\"7\", \"bwbWbwBwB\")\n _encoding.Add(\"8\", \"BwbWbwBwb\")\n _encoding.Add(\"9\", \"bwBWbwBwb\")\n _encoding.Add(\"A\", \"BwbwbWbwB\")\n _encoding.Add(\"B\", \"bwBwbWbwB\")\n _encoding.Add(\"C\", \"BwBwbWbwb\")\n _encoding.Add(\"D\", \"bwbwBWbwB\")\n _encoding.Add(\"E\", \"BwbwBWbwb\")\n _encoding.Add(\"F\", \"bwBwBWbwb\")\n _encoding.Add(\"G\", \"bwbwbWBwB\")\n _encoding.Add(\"H\", \"BwbwbWBwb\")\n _encoding.Add(\"I\", \"bwBwbWBwb\")\n _encoding.Add(\"J\", \"bwbwBWBwb\")\n _encoding.Add(\"K\", \"BwbwbwbWB\")\n _encoding.Add(\"L\", \"bwBwbwbWB\")\n _encoding.Add(\"M\", \"BwBwbwbWb\")\n _encoding.Add(\"N\", \"bwbwBwbWB\")\n _encoding.Add(\"O\", \"BwbwBwbWb\")\n _encoding.Add(\"P\", \"bwBwBwbWb\")\n _encoding.Add(\"Q\", \"bwbwbwBWB\")\n _encoding.Add(\"R\", \"BwbwbwBWb\")\n _encoding.Add(\"S\", \"bwBwbwBWb\")\n _encoding.Add(\"T\", \"bwbwBwBWb\")\n _encoding.Add(\"U\", \"BWbwbwbwB\")\n _encoding.Add(\"V\", \"bWBwbwbwB\")\n _encoding.Add(\"W\", \"BWBwbwbwb\")\n _encoding.Add(\"X\", \"bWbwBwbwB\")\n _encoding.Add(\"Y\", \"BWbwBwbwb\")\n _encoding.Add(\"Z\", \"bWBwBwbwb\")\n End Sub\n\n Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n BarcodeCode39()\n Dim barcode As String = String.Empty\n If Not IsNothing(Request(\"barcode\")) AndAlso Not (Request(\"barcode\").Length = 0) Then\n barcode = Request(\"barcode\")\n Response.ContentType = \"image/png\"\n Response.AddHeader(\"Content-Disposition\", String.Format(\"attachment; filename=barcode_{0}.png\", barcode))\n\n 'TODO: Depending on the length of the string, determine how wide the image will be\n GenerateBarcodeImage(250, 140, barcode).WriteTo(Response.OutputStream)\n End If\n End Sub\n\n Protected Function getBCSymbolColor(ByVal symbol As String) As System.Drawing.Brush\n getBCSymbolColor = Brushes.Black\n If symbol = \"W\" Or symbol = \"w\" Then\n getBCSymbolColor = Brushes.White\n End If\n End Function\n\n Protected Function getBCSymbolWidth(ByVal symbol As String) As Short\n getBCSymbolWidth = _narrowBarWidth\n If symbol = \"B\" Or symbol = \"W\" Then\n getBCSymbolWidth = _wideBarWidth\n End If\n End Function\n\n Protected Overridable Function GenerateBarcodeImage(ByVal imageWidth As Short, ByVal imageHeight As Short, ByVal Code As String) As MemoryStream\n 'create a new bitmap\n Dim b As New Bitmap(imageWidth, imageHeight, Imaging.PixelFormat.Format32bppArgb)\n\n 'create a canvas to paint on\n Dim canvas As New Rectangle(0, 0, imageWidth, imageHeight)\n\n 'draw a white background\n Dim g As Graphics = Graphics.FromImage(b)\n g.FillRectangle(Brushes.White, 0, 0, imageWidth, imageHeight)\n\n 'write the unaltered code at the bottom\n 'TODO: truely center this text\n Dim textBrush As New SolidBrush(Color.Black)\n g.DrawString(Code, New Font(\"Courier New\", 12), textBrush, 100, 110)\n\n 'Code has to be surrounded by asterisks to make it a valid Code39 barcode\n Dim UseCode As String = String.Format(\"{0}{1}{0}\", \"*\", Code)\n\n 'Start drawing at 10, 10\n Dim XPosition As Short = 10\n Dim YPosition As Short = 10\n\n Dim invalidCharacter As Boolean = False\n Dim CurrentSymbol As String = String.Empty\n\n For j As Short = 0 To CShort(UseCode.Length - 1)\n CurrentSymbol = UseCode.Substring(j, 1)\n 'check if symbol can be used\n If Not IsNothing(_encoding(CurrentSymbol)) Then\n Dim EncodedSymbol As String = _encoding(CurrentSymbol).ToString\n\n For i As Short = 0 To CShort(EncodedSymbol.Length - 1)\n Dim CurrentCode As String = EncodedSymbol.Substring(i, 1)\n g.FillRectangle(getBCSymbolColor(CurrentCode), XPosition, YPosition, getBCSymbolWidth(CurrentCode), _barHeight)\n XPosition = XPosition + getBCSymbolWidth(CurrentCode)\n Next\n\n 'After each written full symbol we need a whitespace (narrow width)\n g.FillRectangle(getBCSymbolColor(\"w\"), XPosition, YPosition, getBCSymbolWidth(\"w\"), _barHeight)\n XPosition = XPosition + getBCSymbolWidth(\"w\")\n Else\n invalidCharacter = True\n End If\n Next\n\n 'errorhandling when an invalidcharacter is found\n If invalidCharacter Then\n g.FillRectangle(Brushes.White, 0, 0, imageWidth, imageHeight)\n g.DrawString(\"Invalid characters found,\", New Font(\"Courier New\", 8), textBrush, 0, 0)\n g.DrawString(\"no barcode generated\", New Font(\"Courier New\", 8), textBrush, 0, 10)\n g.DrawString(\"Input was: \", New Font(\"Courier New\", 8), textBrush, 0, 30)\n g.DrawString(Code, New Font(\"Courier New\", 8), textBrush, 0, 40)\n End If\n\n 'write the image into a memorystream\n Dim ms As New MemoryStream\n\n Dim encodingParams As New EncoderParameters\n encodingParams.Param(0) = New EncoderParameter(Encoder.Quality, 100)\n\n Dim encodingInfo As ImageCodecInfo = FindCodecInfo(\"PNG\")\n\n b.Save(ms, encodingInfo, encodingParams)\n\n 'dispose of the object we won't need any more\n g.Dispose()\n b.Dispose()\n\n Return ms\n End Function\n\n Protected Overridable Function FindCodecInfo(ByVal codec As String) As ImageCodecInfo\n Dim encoders As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders\n For Each e As ImageCodecInfo In encoders\n If e.FormatDescription.Equals(codec) Then Return e\n Next\n Return Nothing\n End Function\nEnd Class\n"
},
{
"answer_id": 294975,
"author": "CMPalmer",
"author_id": 14894,
"author_profile": "https://Stackoverflow.com/users/14894",
"pm_score": 1,
"selected": false,
"text": "Barcode39 code39 = new Barcode39();\ncode39.Code = \"Whatever You're Encoding\";\n"
},
{
"answer_id": 26901212,
"author": "civ",
"author_id": 4246566,
"author_profile": "https://Stackoverflow.com/users/4246566",
"pm_score": 0,
"selected": false,
"text": " Public Class code39\n Private bitsCode As ArrayList\n\n Public Sub New()\n bitsCode = New ArrayList\n bitsCode.Add(New String(3) {\"0001101\", \"0100111\", \"1110010\", \"000000\"})\n bitsCode.Add(New String(3) {\"0011001\", \"0110011\", \"1100110\", \"001011\"})\n bitsCode.Add(New String(3) {\"0010011\", \"0011011\", \"1101100\", \"001101\"})\n bitsCode.Add(New String(3) {\"0111101\", \"0100001\", \"1000010\", \"001110\"})\n bitsCode.Add(New String(3) {\"0100011\", \"0011101\", \"1011100\", \"010011\"})\n bitsCode.Add(New String(3) {\"0110001\", \"0111001\", \"1001110\", \"011001\"})\n bitsCode.Add(New String(3) {\"0101111\", \"0000101\", \"1010000\", \"011100\"})\n bitsCode.Add(New String(3) {\"0111011\", \"0010001\", \"1000100\", \"010101\"})\n bitsCode.Add(New String(3) {\"0110111\", \"0001001\", \"1001000\", \"010110\"})\n bitsCode.Add(New String(3) {\"0001011\", \"0010111\", \"1110100\", \"011010\"})\n End Sub\n\n Public Function Generate(ByVal Code As String) As Image\n Dim a As Integer = 0\n Dim b As Integer = 0\n Dim imgCode As Image\n Dim g As Graphics\n Dim i As Integer\n Dim bCode As Byte()\n Dim bitCode As Byte()\n Dim tmpFont As Font\n\n If Code.Length <> 12 Or Not IsNumeric(Code.Replace(\".\", \"_\").Replace(\",\", \"_\")) Then Throw New Exception(\"Le code doit être composé de 12 chiffres\")\n\n ReDim bCode(12)\n For i = 0 To 11\n bCode(i) = CInt(Code.Substring(i, 1))\n If (i Mod 2) = 1 Then\n b += bCode(i)\n Else\n a += bCode(i)\n End If\n Next\n\n i = (a + (b * 3)) Mod 10\n If i = 0 Then\n bCode(12) = 0\n Else\n bCode(12) = 10 - i\n End If\n bitCode = getBits(bCode)\n\n tmpFont = New Font(\"times new roman\", 14, FontStyle.Regular, GraphicsUnit.Pixel)\n imgCode = New Bitmap(110, 50)\n g = Graphics.FromImage(imgCode)\n g.Clear(Color.White)\n\n g.DrawString(Code.Substring(0, 1), tmpFont, Brushes.Black, 2, 30)\n a = g.MeasureString(Code.Substring(0, 1), tmpFont).Width\n\n For i = 0 To bitCode.Length - 1\n If i = 2 Then\n g.DrawString(Code.Substring(1, 6), tmpFont, Brushes.Black, a, 30)\n ElseIf i = 48 Then\n g.DrawString(Code.Substring(7, 5) & bCode(12).ToString, tmpFont, Brushes.Black, a, 30)\n End If\n\n If i = 0 Or i = 2 Or i = 46 Or i = 48 Or i = 92 Or i = 94 Then\n If bitCode(i) = 1 Then 'noir\n g.DrawLine(Pens.Black, a, 0, a, 40)\n a += 1\n End If\n Else\n If bitCode(i) = 1 Then 'noir\n g.DrawLine(Pens.Black, a, 0, a, 30)\n a += 1\n Else 'blanc\n a += 1\n End If\n End If\n Next\n g.Flush()\n Return imgCode\n End Function\n\n Private Function getBits(ByVal bCode As Byte()) As Byte()\n Dim i As Integer\n Dim res As Byte()\n Dim bits As String = \"101\"\n Dim cle As String = bitsCode(bCode(0))(3)\n For i = 1 To 6\n bits &= bitsCode(bCode(i))(CInt(cle.Substring(i - 1, 1)))\n Next\n bits &= \"01010\"\n For i = 7 To 12\n bits &= bitsCode(bCode(i))(2)\n Next\n bits += \"101\"\n ReDim res(bits.Length - 1)\n For i = 0 To bits.Length - 1\n res(i) = Asc(bits.Chars(i)) - 48\n Next\n Return res\n End Function\n\nEnd Class\n"
},
{
"answer_id": 27896165,
"author": "Belinda Raman",
"author_id": 4444045,
"author_profile": "https://Stackoverflow.com/users/4444045",
"pm_score": 0,
"selected": false,
"text": "Imports System.IO\nImports PQScan.BarcodeCreator\n\nNamespace BarcodeGeneratorVB\nClass Program\n Private Shared Sub Main(args As String())\n Dim barcode As New Barcode()\n\n barcode.Data = \"www.pqscan.com\"\n barcode.BarType = BarCodeType.Code39\n barcode.Width = 300\n barcode.Height = 100\n\n barcode.CreateBarcode(\"code39-vb.jpeg\")\n End Sub\nEnd Class\nEnd Namespace\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5018/"
] |
149,380
|
<p>This is an issue that I've spent hours researching in the past. It seems to me to be something that should have been addressed by modern <a href="http://en.wikipedia.org/wiki/Relational_database_management_system" rel="noreferrer">RDBMS</a> solutions but as yet I have not found anything that really addresses what I see to be an incredibly common need in any Web or Windows application with a database back-end.</p>
<p>I speak of dynamic sorting. In my fantasy world, it should be as simple as something like:</p>
<pre><code>ORDER BY @sortCol1, @sortCol2
</code></pre>
<p>This is the canonical example given by newbie SQL and <a href="http://en.wikipedia.org/wiki/Stored_procedure" rel="noreferrer">Stored Procedure</a> developers all over forums across the Internet. "Why isn't this possible?" they ask. Invariably, somebody eventually comes along to lecture them about the compiled nature of stored procedures, of execution plans in general, and all sorts of other reasons why it isn't possible to put a parameter directly into an <code>ORDER BY</code> clause.</p>
<hr>
<p>I know what some of you are already thinking: "Let the client do the sorting, then." Naturally, this offloads the work from your database. In our case though, our database servers aren't even breaking a sweat 99% of the time and they aren't even multi-core yet or any of the other myriad improvements to system architecture that happen every 6 months. For this reason alone, having our databases handle sorting wouldn't be a problem. Additionally, databases are <em>very</em> good at sorting. They are optimized for it and have had years to get it right, the language for doing it is incredibly flexible, intuitive, and simple and above all any beginner SQL writer knows how to do it and even more importantly they know how to edit it, make changes, do maintenance, etc. When your databases are far from being taxed and you just want to simplify (and shorten!) development time this seems like an obvious choice.</p>
<p>Then there's the web issue. I've played around with JavaScript that will do client-side sorting of HTML tables, but they inevitably aren't flexible enough for my needs and, again, since my databases aren't overly taxed and can do sorting really <em>really</em> easily, I have a hard time justifying the time it would take to re-write or roll-my-own JavaScript sorter. The same generally goes for server-side sorting, though it is already probably much preferred over JavaScript. I'm not one that particularly likes the overhead of DataSets, so sue me.</p>
<p>But this brings back the point that it isn't possible — or rather, not easily. I've done, with prior systems, an incredibly hack way of getting dynamic sorting. It wasn't pretty, nor intuitive, simple, or flexible and a beginner SQL writer would be lost within seconds. Already this is looking to be not so much a "solution" but a "complication."</p>
<hr>
<p>The following examples are not meant to expose any sort of best practices or good coding style or anything, nor are they indicative of my abilities as a T-SQL programmer. They are what they are and I fully admit they are confusing, bad form, and just plain hack.</p>
<p>We pass an integer value as a parameter to a stored procedure (let's call the parameter just "sort") and from that we determine a bunch of other variables. For example... let's say sort is 1 (or the default):</p>
<pre><code>DECLARE @sortCol1 AS varchar(20)
DECLARE @sortCol2 AS varchar(20)
DECLARE @dir1 AS varchar(20)
DECLARE @dir2 AS varchar(20)
DECLARE @col1 AS varchar(20)
DECLARE @col2 AS varchar(20)
SET @col1 = 'storagedatetime';
SET @col2 = 'vehicleid';
IF @sort = 1 -- Default sort.
BEGIN
SET @sortCol1 = @col1;
SET @dir1 = 'asc';
SET @sortCol2 = @col2;
SET @dir2 = 'asc';
END
ELSE IF @sort = 2 -- Reversed order default sort.
BEGIN
SET @sortCol1 = @col1;
SET @dir1 = 'desc';
SET @sortCol2 = @col2;
SET @dir2 = 'desc';
END
</code></pre>
<p>You can already see how if I declared more @colX variables to define other columns I could really get creative with the columns to sort on based on the value of "sort"... to use it, it usually ends up looking like the following incredibly messy clause:</p>
<pre><code>ORDER BY
CASE @dir1
WHEN 'desc' THEN
CASE @sortCol1
WHEN @col1 THEN [storagedatetime]
WHEN @col2 THEN [vehicleid]
END
END DESC,
CASE @dir1
WHEN 'asc' THEN
CASE @sortCol1
WHEN @col1 THEN [storagedatetime]
WHEN @col2 THEN [vehicleid]
END
END,
CASE @dir2
WHEN 'desc' THEN
CASE @sortCol2
WHEN @col1 THEN [storagedatetime]
WHEN @col2 THEN [vehicleid]
END
END DESC,
CASE @dir2
WHEN 'asc' THEN
CASE @sortCol2
WHEN @col1 THEN [storagedatetime]
WHEN @col2 THEN [vehicleid]
END
END
</code></pre>
<p>Obviously this is a very stripped down example. The real stuff, since we usually have four or five columns to support sorting on, each with possible secondary or even a third column to sort on in addition to that (for example date descending then sorted secondarily by name ascending) and each supporting bi-directional sorting which effectively doubles the number of cases. Yeah... it gets hairy really quick.</p>
<p>The idea is that one could "easily" change the sort cases such that vehicleid gets sorted before the storagedatetime... but the pseudo-flexibility, at least in this simple example, really ends there. Essentially, each case that fails a test (because our sort method doesn't apply to it this time around) renders a NULL value. And thus you end up with a clause that functions like the following:</p>
<pre><code>ORDER BY NULL DESC, NULL, [storagedatetime] DESC, blah blah
</code></pre>
<p>You get the idea. It works because SQL Server effectively ignores null values in order by clauses. This is incredibly hard to maintain, as anyone with any basic working knowledge of SQL can probably see. If I've lost any of you, don't feel bad. It took us a long time to get it working and we still get confused trying to edit it or create new ones like it. Thankfully it doesn't need changing often, otherwise it would quickly become "not worth the trouble."</p>
<p>Yet it <em>did</em> work.</p>
<hr>
<p>My question is then: <strong>is there a better way?</strong></p>
<p>I'm okay with solutions other than Stored Procedure ones, as I realize it may just not be the way to go. Preferably, I'd like to know if anyone can do it better within the Stored Procedure, but if not, how do you all handle letting the user dynamically sort tables of data (bi-directionally, too) with ASP.NET?</p>
<p>And thank you for reading (or at least skimming) such a long question!</p>
<p>PS: Be glad I didn't show my example of a stored procedure that supports dynamic sorting, dynamic filtering/text-searching of columns, pagination via ROWNUMBER() OVER, <em>AND</em> try...catch with transaction rollbacking on errors... "behemoth-sized" doesn't even begin to describe them.</p>
<hr>
<p><strong>Update:</strong></p>
<ul>
<li>I would like to <strong>avoid dynamic SQL</strong>. Parsing a string together and running an EXEC on it defeats a lot of the purpose of having a stored procedure in the first place. Sometimes I wonder though if the cons of doing such a thing wouldn't be worth it, at least in these special dynamic sorting cases. Still, I always feel dirty whenever I do dynamic SQL strings like that — like I'm still living in the Classic ASP world.</li>
<li>A lot of the reason we want stored procedures in the first place is for <strong>security</strong>. I don't get to make the call on security concerns, only suggest solutions. With SQL Server 2005 we can set permissions (on a per-user basis if need be) at the schema level on individual stored procedures and then deny any queries against the tables directly. Critiquing the pros and cons of this approach is perhaps for another question, but again it's not my decision. I'm just the lead code monkey. :)</li>
</ul>
|
[
{
"answer_id": 149549,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 7,
"selected": false,
"text": "order by\ncase when @SortExpr = 'CustomerName' and @SortDir = 'ASC' \n then CustomerName end asc, \ncase when @SortExpr = 'CustomerName' and @SortDir = 'DESC' \n then CustomerName end desc,\n...\n @SortExpr @SortDir"
},
{
"answer_id": 149586,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 2,
"selected": false,
"text": "create procedure uspCallAndSort\n(\n @sql varchar(2048), --exec dbo.uspSomeProcedure arg1,'arg2',etc.\n @sortClause varchar(512) --comma-delimited field list\n)\nAS\ninsert into #tmp EXEC(@sql)\ndeclare @msql varchar(3000)\nset @msql = 'select * from #tmp order by ' + @sortClause\nEXEC(@msql)\ndrop table #tmp\nGO\n"
},
{
"answer_id": 150173,
"author": "Ron Savage",
"author_id": 12476,
"author_profile": "https://Stackoverflow.com/users/12476",
"pm_score": 3,
"selected": false,
"text": "select * from dbo.fn_myData() where ... order by ..."
},
{
"answer_id": 150979,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 2,
"selected": false,
"text": "create table #temp ( your columns )\n\ninsert #temp\nexec foobar\n\nselect * from #temp order by whatever\n"
},
{
"answer_id": 151764,
"author": "Jason DeFontes",
"author_id": 6159,
"author_profile": "https://Stackoverflow.com/users/6159",
"pm_score": 5,
"selected": false,
"text": "SELECT\n s.*\nFROM\n (SELECT\n CASE @SortCol1\n WHEN 'Foo' THEN t.Foo\n WHEN 'Bar' THEN t.Bar\n ELSE null\n END as SortCol1,\n CASE @SortCol2\n WHEN 'Foo' THEN t.Foo\n WHEN 'Bar' THEN t.Bar\n ELSE null\n END as SortCol2,\n t.*\n FROM\n MyTable t) as s\nORDER BY\n CASE WHEN @dir1 = 'ASC' THEN SortCol1 END ASC,\n CASE WHEN @dir1 = 'DESC' THEN SortCol1 END DESC,\n CASE WHEN @dir2 = 'ASC' THEN SortCol2 END ASC,\n CASE WHEN @dir2 = 'DESC' THEN SortCol2 END DESC\n"
},
{
"answer_id": 836798,
"author": "dotjoe",
"author_id": 40822,
"author_profile": "https://Stackoverflow.com/users/40822",
"pm_score": 2,
"selected": false,
"text": "declare @o int;\nset @o = -1;\n\ndeclare @sql nvarchar(2000);\nset @sql = N'select * from table order by ' + \n cast(abs(@o) as varchar) + case when @o < 0 then ' desc' else ' asc' end + ';'\n\nexec sp_executesql @sql\n declare @cols varchar(100);\nset @cols = '1 -2 3 6';\n\ndeclare @order_by varchar(200)\n\nselect @order_by = isnull(@order_by + ', ', '') + \n cast(abs(number) as varchar) + \n case when number < 0 then ' desc' else '' end\nfrom dbo.iter_intlist_to_tbl(@cols) order by listpos\n\nprint @order_by\n"
},
{
"answer_id": 3390130,
"author": "dave",
"author_id": 391047,
"author_profile": "https://Stackoverflow.com/users/391047",
"pm_score": 3,
"selected": false,
"text": "SELECT\n name_last,\n name_first,\n CASE @sortCol WHEN 'name_last' THEN [name_last] ELSE 0 END as mySort\nFROM\n table\nORDER BY \n mySort\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7290/"
] |
149,388
|
<p>Was wondering if anyone knows, or has pointers to good documentation that discusses, the low-level implementation details of Cocoa's 'performSelectorOnMainThread:' method.</p>
<p>My best guess, and one I think is probably pretty close, is that it uses mach ports or an abstraction on top of them to provide intra-thread communication, passing selector information along as part of the mach message.</p>
<p>Right? Wrong? Thanks!</p>
<p><strong>Update 09:39AMPST</strong></p>
<p>Thank you Evan DiBiase and Mecki for the answers, but to clarify: I understand what happens in the run loop, but what I'm looking for an answer to is; "<em>where</em> is the method getting queued? <em>how</em> is the selector information getting passed into the queue?" Looking for more than Apple's doc info: I've read 'em</p>
<p><strong>Update 14:21PST</strong></p>
<p>Chris Hanson brings up a good point in a comment: my objective here is not to learn the underlying mechanisms in order to take advantage of them in my own code. Rather, I'm just interested in a better conceptual understanding of the process of signaling another thread to execute code. As I said, my own research leads me to believe that it's takes advantage of mach messaging for IPC to pass selector information between threads, but I'm specifically looking for <strong>concrete</strong> information on what is happening, so I can be sure I'm understanding things <em>correctly</em>. Thanks! </p>
<p><strong>Update 03/06/09</strong></p>
<p>I've opened a bounty on this question because I'd really like to see it answered, but if you are trying to collect please make sure you read <strong>everything</strong>, including all currently posed answers, comments to both these answers and to my original question, and the update text I posted above. I'm look for the <strong>lowest-level detail</strong> of the mechanism used by <code>performSelectorOnMainThread:</code> and the like, and as I mentioned earlier, I suspect it has something to do with Mach ports but I'd really like to know for sure. The bounty will not be awarded unless I can <strong>confirm</strong> the answer given is correct. Thanks everyone!</p>
|
[
{
"answer_id": 149448,
"author": "Evan DiBiase",
"author_id": 2399475,
"author_profile": "https://Stackoverflow.com/users/2399475",
"pm_score": 2,
"selected": false,
"text": "performSelectorOnMainThread:withObject:waitUntilDone:"
},
{
"answer_id": 149471,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 2,
"selected": false,
"text": "// Main Thread\n\nfor (;;) {\n lock(runloop->runloopLock);\n task = NULL;\n do {\n task = getNextTask(runloop);\n if (!task) {\n // function below unlocks the lock and\n // atomically sends thread to sleep.\n // If thread is woken up again, it will\n // get the lock again before continuing\n // running. See \"man pthread_cond_wait\"\n // as an example function that works\n // this way\n wait_for_notification(runloop->newTasks, runloop->runloopLock);\n }\n } while (!task);\n unlock(runloop->runloopLock);\n processTask(task);\n}\n\n\n// Other thread, perform selector on main thread\n// selector is char *, containing the selector\n// object is void *, reference to object\n\ntimer = createTimerInPast(selector, object);\nrunloop = getRunloopOfMainThread();\nlock(runloop->runloopLock);\naddTask(runloop, timer);\nwake_all_sleeping(runloop->newTasks);\nunlock(runloop->runloopLock);\n"
},
{
"answer_id": 151166,
"author": "Jens Ayton",
"author_id": 6443,
"author_profile": "https://Stackoverflow.com/users/6443",
"pm_score": 0,
"selected": false,
"text": "-performSelectorOn… NSTimer NSTimer CFRunLoopTimer CFRunLoopTimer"
},
{
"answer_id": 620284,
"author": "Tony",
"author_id": 34101,
"author_profile": "https://Stackoverflow.com/users/34101",
"pm_score": 4,
"selected": true,
"text": "@synchronized pthread_mutex_lock 0 mach_msg\n1 CFRunLoopWakeUp\n2 -[NSThread _nq:]\n3 -[NSObject(NSThreadPerformAdditions) performSelector:onThread:withObject:waitUntilDone:modes:]\n4 -[NSObject(NSThreadPerformAdditions) performSelectorOnMainThread:withObject:waitUntilDone:]\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23498/"
] |
149,394
|
<p>I have a winforms application, the issue has to do with threading.
Since I am calling 'MyCustomCode() which creates a new thread, and calls the method
'SomeMethod()' which then accesses MessageBox.Show(...).</p>
<p>The problem has to do with threading, since the newly created thread is trying to access
a control that was created on another thread.</p>
<p>I am getting the error:</p>
<p>Cross-thread operation not valid: Control 'TestForm' accessed from a thread other than the thread it was created on.</p>
<pre><code>public TestForm()
{
InitializeComponent();
// custom code
//
MyCustomCode();
}
public void SomeMethod()
{
// ***** This causes an error ****
MessageBox.Show(this,
ex.Message,
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
}
private void InitializeAutoUpdater()
{
// Seperate thread is spun to keep polling for updates
ThreadStart ts = new ThreadStart(SomeMethod);
pollThread = new Thread(ts);
pollThread.Start();
}
</code></pre>
<p><b>Update</b></p>
<p>If you look at this example <a href="http://www.codeproject.com/KB/cs/vanillaupdaterblock.aspx" rel="noreferrer">http://www.codeproject.com/KB/cs/vanillaupdaterblock.aspx</a>, the method CheckAndUpdate is calling MessageBox.Show(..) that is what my problem is. I would have thought that code was good to go!</p>
<p><b>Funny thing</b> is that this code was working just fine on Friday???</p>
|
[
{
"answer_id": 149404,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 3,
"selected": false,
"text": "public delegate void InvokeDelegate();\n\npublic void SomeMethod()\n{\n\n button1.Invoke((InvokeDelegate)doUIStuff);\n\n\n}\n\n\nvoid doUIStuff()\n{\n MessageBox.Show(this, \n ex.Message, \n \"Error\", \n MessageBoxButtons.OK, \n MessageBoxIcon.Error\n );\n}\n"
},
{
"answer_id": 149436,
"author": "Ron Savage",
"author_id": 12476,
"author_profile": "https://Stackoverflow.com/users/12476",
"pm_score": 0,
"selected": false,
"text": "'*******************************************************************\n' Get a new processor and fire it off on a new thread.\n'*******************************************************************\nfpProc = New Processor(confTable, paramFile, keyCount)\nAddHandler fpProc.LogEntry, AddressOf LogEntry_Handler\nDim myThread As System.Threading.Thread = New System.Threading.Thread(AddressOf fpProc.ProcessEntry)\nmyThread.Start()\n '*************************************************************************\n' Sub: LogEntry_Handler()\n' Author: Ron Savage\n' Date: 08/29/2007\n'\n' This routine handles the LogEntry events raised by the Processor class\n' running in a thread.\n'*************************************************************************\nPrivate Sub LogEntry_Handler(ByVal logLevel As Integer, ByVal logMsg As String) Handles fProc.LogEntry\n writeLogMessage(logMsg);\nEnd Sub\n"
},
{
"answer_id": 149444,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 3,
"selected": false,
"text": "protected delegate void someGuiFunctionDelegate(int iParam);\n\nprotected void someGuiFunction(int iParam)\n{\n if (this.InvokeRequired)\n {\n someGuiFunctionDelegate dlg = new \n someGuiFunctionDelegate(this.someGuiFunction);\n this.Invoke(dlg, new object[] { iParam });\n return;\n }\n\n //do something with the GUI control here\n}\n"
},
{
"answer_id": 2016581,
"author": "Joel Barsotti",
"author_id": 37154,
"author_profile": "https://Stackoverflow.com/users/37154",
"pm_score": 0,
"selected": false,
"text": "public delegate void InvokeDelegate(string errMessage); \n\n public void SomeMethod() \n { \n doUIStuff(\"my error message\");\n } \n\n\n void doUIStuff(string errMessage) \n { \n if (button1.InvokeRequired)\n button1.Invoke((InvokeDelegate)doUIStuff(errMessage)); \n else\n {\n MessageBox.Show(this, \n ex.Message, \n errMessage, \n MessageBoxButtons.OK, \n MessageBoxIcon.Error \n ); \n }\n } \n"
},
{
"answer_id": 3903823,
"author": "Arical",
"author_id": 471982,
"author_profile": "https://Stackoverflow.com/users/471982",
"pm_score": 1,
"selected": false,
"text": "public static void Manipulate<T>(this T control, Action<T> action) where T : Control\n{\n if (control.InvokeRequired)\n {\n control.Invoke(new Action<T, Action<T>>(Manipulate),\n new object[] { control, action });\n }\n else\n { action(control); }\n}\n someLabel.Manipulate(lbl => lbl.Text = \"Something\");\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
149,395
|
<p>We have a Windows machine running SQL Server 2005, and we need to be able to run some database queries on it from a Linux box. What are some of the recommended ways of doing this? Ideally, we would want a command-line utility similar to sqlcmd on Windows.</p>
|
[
{
"answer_id": 149418,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 6,
"selected": true,
"text": "$more /etc/freetds/freetds.conf\n[10.0.1.251]\n host = 10.0.1.251\n port = 1433\n tds version = 8.0\n\n$ more /etc/odbc.ini\n[ACCT]\nDriver = /usr/local/freetds/lib/libtdsodbc.so\nDescription = ODBC to SQLServer via FreeTDS\nTrace = No\nServername = 10.0.1.251\nDatabase = accounts_ver8\n"
},
{
"answer_id": 25948864,
"author": "mleu",
"author_id": 2809693,
"author_profile": "https://Stackoverflow.com/users/2809693",
"pm_score": 3,
"selected": false,
"text": "sqlcmd"
},
{
"answer_id": 54808074,
"author": "helvete",
"author_id": 2915423,
"author_profile": "https://Stackoverflow.com/users/2915423",
"pm_score": 0,
"selected": false,
"text": "mssql-cli psql pip sudo sudo pip install mssql-cli\n"
},
{
"answer_id": 68340084,
"author": "mwag",
"author_id": 3160967,
"author_profile": "https://Stackoverflow.com/users/3160967",
"pm_score": 1,
"selected": false,
"text": "tsql freebcp tsql"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4828/"
] |
149,421
|
<p>How does Stackoverflow implement the resizable textarea?</p>
<p>Is that something they rolled themselves or is it a publicly available component that I can easily attach to textareas on my sites? </p>
<p>I found this question and it doesn't quite do what I want.</p>
<p><a href="https://stackoverflow.com/questions/7477/autosizing-textarea">autosizing-textarea</a></p>
<p>That talks more about automatically resizing textareas whereas I want the little grab-area that you can drag up and down.</p>
|
[
{
"answer_id": 29240767,
"author": "benshope",
"author_id": 1865305,
"author_profile": "https://Stackoverflow.com/users/1865305",
"pm_score": 0,
"selected": false,
"text": "angular.module('app').directive('textarea', function() {\n return {\n restrict: 'E',\n controller: function($scope, $element) {\n $element.css('overflow-y','hidden');\n $element.css('resize','none');\n resetHeight();\n adjustHeight();\n\n function resetHeight() {\n $element.css('height', 0 + 'px');\n }\n\n function adjustHeight() {\n var height = angular.element($element)[0]\n .scrollHeight + 1;\n $element.css('height', height + 'px');\n $element.css('max-height', height + 'px');\n }\n\n function keyPress(event) {\n // this handles backspace and delete\n if (_.contains([8, 46], event.keyCode)) {\n resetHeight();\n }\n adjustHeight();\n }\n\n $element.bind('keyup change blur', keyPress);\n\n }\n };\n});\n angular.module('app').directive('expandingTextarea', function() {\n return {\n restrict: 'A',\n"
},
{
"answer_id": 48460843,
"author": "Martin Prestone",
"author_id": 8457803,
"author_profile": "https://Stackoverflow.com/users/8457803",
"pm_score": 0,
"selected": false,
"text": "<textarea oninput='this.style.height = \"\";this.style.height = this.scrollHeight + \"px\"'></textarea>\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] |
149,439
|
<p>How can you avoid circular dependencies when you're designing two classes with a producer/consumer relationship? Here ListenerImpl needs a reference to Broadcaster in order to register/unregister itself, and Broadcaster needs a reference back to the Listeners in order to send messages. This example is in Java but it can apply to any OO language.</p>
<pre><code>public interface Listener {
void callBack(Object arg);
}
public class ListenerImpl implements Listener {
public ListenerImpl(Broadcaster b) { b.register(this); }
public void callBack(Object arg) { ... }
public void shutDown() { b.unregister(this); }
}
public class Broadcaster {
private final List listeners = new ArrayList();
public void register(Listener lis) { listeners.add(lis); }
public void unregister(Listener lis) {listeners.remove(lis); }
public void broadcast(Object arg) { for (Listener lis : listeners) { lis.callBack(arg); } }
}
</code></pre>
|
[
{
"answer_id": 149457,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 4,
"selected": true,
"text": " Listener\n ^ ^\n / \\\n / \\\nBroadcaster <-- ListenerImpl\n"
},
{
"answer_id": 149478,
"author": "Sunny Milenov",
"author_id": 8220,
"author_profile": "https://Stackoverflow.com/users/8220",
"pm_score": 0,
"selected": false,
"text": "public class ListenerImpl implements Listener {\n public Foo() {}\n public void registerWithBroadcaster(Broadcaster b){ b.register(this); isRegistered = true;}\n public void callBack(Object arg) { if (!isRegistered) throw ... else ... }\n public void shutDown() { isRegistered = false; }\n}\n\npublic class Broadcaster {\n private final List listeners = new ArrayList();\n public void register(Listener lis) { listeners.add(lis); }\n public void unregister(Listener lis) {listeners.remove(lis); }\n public void broadcast(Object arg) { for (Listener lis : listeners) { if (lis.isRegistered) lis.callBack(arg) else unregister(lis); } }\n}\n"
},
{
"answer_id": 149693,
"author": "Mikael Jansson",
"author_id": 18753,
"author_profile": "https://Stackoverflow.com/users/18753",
"pm_score": 3,
"selected": false,
"text": "(defclass broadcaster ()\n ((listeners :accessor listeners\n :initform '())))\n\n(defgeneric add-listener (broadcaster listener)\n (:documentation \"Add a listener (a function taking one argument)\n to a broadcast's list of interested parties\"))\n\n(defgeneric remove-listener (broadcaster listener)\n (:documentation \"Reverse of add-listener\"))\n\n(defgeneric broadcast (broadcaster object)\n (:documentation \"Broadcast an object to all registered listeners\"))\n\n(defmethod add-listener (broadcaster listener)\n (pushnew listener (listeners broadcaster)))\n\n(defmethod remove-listener (broadcaster listener)\n (let ((listeners (listeners broadcaster)))\n (setf listeners (remove listener listeners))))\n\n(defmethod broadcast (broadcaster object)\n (dolist (listener (listeners broadcaster))\n (funcall listener object)))\n (defclass direct-broadcaster (broadcaster)\n ((latest-broadcast :accessor latest-broadcast)\n (latest-broadcast-p :initform nil))\n (:documentation \"I broadcast the latest broadcasted object when a new listener is added\"))\n\n(defmethod add-listener :after ((broadcaster direct-broadcaster) listener)\n (when (slot-value broadcaster 'latest-broadcast-p)\n (funcall listener (latest-broadcast broadcaster))))\n\n(defmethod broadcast :after ((broadcaster direct-broadcaster) object)\n (setf (slot-value broadcaster 'latest-broadcast-p) t)\n (setf (latest-broadcast broadcaster) object))\n Lisp> (let ((broadcaster (make-instance 'broadcaster)))\n (add-listener broadcaster \n #'(lambda (obj) (format t \"I got myself a ~A object!~%\" obj)))\n (add-listener broadcaster \n #'(lambda (obj) (format t \"I has object: ~A~%\" obj)))\n (broadcast broadcaster 'cheezburger))\n\nI has object: CHEEZBURGER\nI got myself a CHEEZBURGER object!\n\nLisp> (defparameter *direct-broadcaster* (make-instance 'direct-broadcaster))\n (add-listener *direct-broadcaster*\n #'(lambda (obj) (format t \"I got myself a ~A object!~%\" obj)))\n (broadcast *direct-broadcaster* 'kitty)\n\nI got myself a KITTY object!\n\nLisp> (add-listener *direct-broadcaster*\n #'(lambda (obj) (format t \"I has object: ~A~%\" obj)))\n\nI has object: KITTY\n"
},
{
"answer_id": 325391,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 0,
"selected": false,
"text": "Broadcaster = Object:subclass()\n\nfunction Broadcaster:initialize()\n self._listeners = {}\nend\n\nfunction Broadcaster:register(listener)\n self._listeners[listener] = true\nend\n\nfunction Broadcaster:unregister(listener)\n self._listeners[listener] = nil\nend\nfunction Broadcaster:broadcast(...)\n for listener in pairs(self._listeners) do\n listener(...)\n end\nend\n --# Listener\nListener = Object:subclass()\nfunction Listener:callback(arg)\n self:subclassResponsibility()\nend\n\n--# ListenerImpl\nfunction ListenerImpl:initialize(broadcaster)\n self._broadcaster = broadcaster\n broadcaster:register(this)\nend\nfunction ListenerImpl:callback(arg)\n --# ...\nend\nfunction ListenerImpl:shutdown()\n self._broadcaster:unregister(self)\nend\n\n--# Broadcaster\nfunction Broadcaster:initialize()\n self._listeners = {}\nend\nfunction Broadcaster:register(listener)\n self._listeners[listener] = true\nend\nfunction Broadcaster:unregister(listener)\n self._listeners[listener] = nil\nend\nfunction Broadcaster:broadcast(arg)\n for listener in pairs(self._listeners) do\n listener:callback(arg)\n end\nend\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16399/"
] |
149,463
|
<p>I have this code inside a class:</p>
<pre><code>void SendStones()
{
int currenthole = hole;
int lastplace = 0;
for(int i=0;i<stns.size();i++)
{
while(1)
{//Calculate new currenthole
if(currenthole == 13) { currenthole = 7; break;}
if(currenthole == 14) { currenthole = 6; break;}
if((currenthole<=12 && currenthole > 7) || (currenthole<=6 && currenthole > 1)) { currenthole--; break;}
}
lastplace = stns.size()-1;
hole[currenthole]->ReciveStone(stns[lastplace]);//PROBLEM
stns.pop_back();
}
}
vector<Stones*> stns;
</code></pre>
<p>so it makes this error:
invalid types `int[int]' for array subscript </p>
<p>what's the problem?i don't understand.
Thanks.</p>
|
[
{
"answer_id": 149562,
"author": "moswald",
"author_id": 8368,
"author_profile": "https://Stackoverflow.com/users/8368",
"pm_score": 0,
"selected": false,
"text": "int currenthole = hole;\n if(currenthole == 13) { currenthole = 7; break;}\n if(currenthole == 14) { currenthole = 6; break;}\n if((currenthole<=12 && currenthole > 7) || (currenthole<=6 && currenthole > 1)) { currenthole--; break;}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
149,474
|
<p>This XML file contained archived news stories for all of last year. I was asked to sort these stories by story categor[y|ies] into new XML files.</p>
<pre><code>big_story_export.xml
</code></pre>
<p>turns into</p>
<pre><code>lifestyles.xml
food.xml
nascar.xml
</code></pre>
<p>...and so on.</p>
<p>I got the job done using a one-off python script, <em>however</em>, <strong>I originally attempted this using XSLT</strong>. This resulted in frustration as my XPATH selections were crapping the bed. Test files were transformed perfectly, but putting the big file up against my style sheet resulted in ...<em>nothing</em>.</p>
<p>What strategies do you recommend for ensuring that files like this will run through XSLT? <em>This was handed to me by a vendor, so imagine that I don't have a lot of leverage when it comes to defining the structure of this file.</em></p>
<p>If you guys want code samples, I'll put some together. </p>
<p>If anything, I'd be satisfied with some tips for making XML+XSLT work together smoothly.</p>
<hr>
<p>@Sklivvz</p>
<p>I was using python's libxml2 & libxslt to process this. I'm looking into xsltproc now. </p>
<p>It seems like a good tool for these one-off situations. Thanks!</p>
<hr>
<p>@diomidis-spinellis</p>
<p>It's well-formed, though (as mentioned) I don't have faculties to discover it's validity.</p>
<p>As for writing a Schema, I like the idea. </p>
<p>The amount of time I invest in getting this one file validated would be impractical if it were a one-time thing, though I foresee having to handle more files like this from our vendor.</p>
<p>Writing a schema (and submitting it to the vendor) would be an excellent long-term strategy for managing XML funk like this. Thanks!</p>
|
[
{
"answer_id": 149495,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 2,
"selected": false,
"text": "xsltproc"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22491/"
] |
149,479
|
<p>Well, it seems simple enough, but I can't find a way to add a caption to an equation.
The caption is needed to explain the variables used in the equation, so some kind of table-like structure to keep it all aligned and pretty would be great.</p>
|
[
{
"answer_id": 149494,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 4,
"selected": false,
"text": "\\newfloat $ ... $ $$ ... $$ begin{equation}... \\caption \\begin{document} \\usepackage{float}\n\\usepackage{aliascnt}\n\\newaliascnt{eqfloat}{equation}\n\\newfloat{eqfloat}{h}{eqflts}\n\\floatname{eqfloat}{Equation}\n\n\\newcommand*{\\ORGeqfloat}{}\n\\let\\ORGeqfloat\\eqfloat\n\\def\\eqfloat{%\n \\let\\ORIGINALcaption\\caption\n \\def\\caption{%\n \\addtocounter{equation}{-1}%\n \\ORIGINALcaption\n }%\n \\ORGeqfloat\n}\n \\begin{eqfloat}\n\\begin{equation}\nf( x ) = ax + b\n\\label{eq:linear}\n\\end{equation}\n\\caption{Caption goes here}\n\\end{eqfloat}\n"
},
{
"answer_id": 149677,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 7,
"selected": true,
"text": "\\caption \\begin{figure}\n\\[ E = m c^2 \\]\n\\caption{A famous equation}\n\\end{figure}\n \\captionof \\[ E = m c^2 \\]\n\\captionof{figure}{A famous equation}\n \\listoffigures eqnarray"
},
{
"answer_id": 47840493,
"author": "MattAllegro",
"author_id": 3543233,
"author_profile": "https://Stackoverflow.com/users/3543233",
"pm_score": 4,
"selected": false,
"text": "\\documentclass{article}\n\\usepackage{caption}\n\n\\DeclareCaptionType{equ}[][]\n%\\captionsetup[equ]{labelformat=empty}\n\n\\begin{document}\n\nSome text\n\n\\begin{equ}[!ht]\n \\begin{equation}\n a=b+c\n \\end{equation}\n\\caption{Caption of the equation}\n\\end{equ}\n\nSome other text\n \n\\end{document}\n caption"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2841/"
] |
149,484
|
<p>I want to create a VB.NET generic factory method that creates instances of classes (as a home-grown inversion of control container). If I pass the interface IDoSomething as the generic parameter, I want to return an instance of DoSomething (that implements IDoSomething). I cannot figure out the syntax of the if statement. I want to write something like:</p>
<pre><code>Public Function Build(Of T) as T
If T Is IDoSomething then
Return New DoSomething()
ElseIf T Is IAndSoOn Then
Return New AndSoOn()
Else
Throw New WhatWereYouThinkingException("Bad")
End If
End Sub
</code></pre>
<p>But this code does not compile.</p>
|
[
{
"answer_id": 149536,
"author": "codeConcussion",
"author_id": 1321,
"author_profile": "https://Stackoverflow.com/users/1321",
"pm_score": 2,
"selected": false,
"text": "Public Function Build(Of T) As T\n Dim foo As Type = GetType(T)\n\n If foo Is GetType(IDoSomething) Then\n Return New DoSomething()\n ...\n End If\nEnd Function\n"
},
{
"answer_id": 149603,
"author": "Drak",
"author_id": 22939,
"author_profile": "https://Stackoverflow.com/users/22939",
"pm_score": 0,
"selected": false,
"text": "Public Function Build(Of T) as T \n If T.gettype Is gettype(IDoSomething) then \n Return New DoSomething() \n ElseIf T.gettype Is gettype(IAndSoOn) Then \n Return New AndSoOn() \n Else \n Throw New WhatWereYouThinkingException(\"Bad\") \n End If \nEnd Sub\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
149,485
|
<p>Like many projects, we deploy to many environments, QA, UA, Developer trunks, etc..</p>
<p>What is the best way to store sensitive configuration parameters in SVN? Or, should you not and just maintain a smaller unversioned file with credentials in it on the server?</p>
<p>Mainly, we do not want to expose production credentials to every developer.</p>
|
[
{
"answer_id": 149590,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 3,
"selected": false,
"text": "setup.default.php setup.php .svnignore $ echo 'setup.php' > .svnignore\n$ svn propset svn:ignore -F .svnignore .\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
149,488
|
<p>I enjoy developing algorithms using the STL, however, I have this recurring problem where my data sets are too large for the heap. </p>
<p>I have been searching for drop-in replacements for STL containers and algorithms which are disk-backed, i.e. the data structures on stored on disk rather than the heap. </p>
<p>A friend recently pointed me towards <a href="http://stxxl.sourceforge.net" rel="noreferrer">stxxl</a>. Before I get too involved with it... Are any other disk-backed STL replacements available that I should be considering? </p>
<p><strong>NOTE: I'm not interested in persistence or embedded databases. Please don't mention boost::serialization, POST++, Relational Template Library, Berkeley DB, sqlite, etc. I am aware of these projects and use them when they are appropriate for my purposes.</strong> </p>
<p><em>UPDATE: Several people have mentioned memory-mapping files and using a custom allocator, good suggestions BTW, but I would point them to the discussion <a href="http://lists.boost.org/Archives/boost/2002/11/39388.php" rel="noreferrer">here</a> where David Abraham suggests that custom iterators would be needed for disk-backed containers. Meaning the custom allocator approach isn't likely to work.</em></p>
|
[
{
"answer_id": 151612,
"author": "Ted",
"author_id": 8965,
"author_profile": "https://Stackoverflow.com/users/8965",
"pm_score": 4,
"selected": true,
"text": "boost::iterator_facade"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14069/"
] |
149,491
|
<p>I've been arguing with my coworkers about Pascal casing (upper camel case) vs. lower <a href="http://en.wikipedia.org/wiki/CamelCase" rel="noreferrer">CamelCasing</a>. They are used to lower camel casing for everything from table names in SQL databases to property naming in C# code but I like Pascal casing better, lower camel casing for variables and Pascal casing for properties:</p>
<pre><code>string firstName;
public string FirstName {
...
}
</code></pre>
<p>But they are used to this:</p>
<pre><code>string _firstname;
public string firstName {
...
}
</code></pre>
<p>I try to keep up with their "standard" so the code looks the same but I just don't like it.</p>
<p>I've seen that at least the .NET framework uses this convention and that is how I try to keep my code, e.g.:</p>
<pre><code>System.Console.WriteLine("string")
</code></pre>
<p>What do you use/prefer and why? I'm sorry if somebody else asked this question but I searched and did not find anything.</p>
<p><strong>Update:</strong>
I've given a method example and not a property but it's the same. As I stated in the first paragraph my colleagues use the Pascal convention for everything (variables, methods, table names, etc.)</p>
|
[
{
"answer_id": 149511,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 0,
"selected": false,
"text": "_localVar"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14533/"
] |
149,500
|
<p>What does the following code do in C/C++?</p>
<pre><code>if (blah(), 5) {
//do something
}
</code></pre>
|
[
{
"answer_id": 149518,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 6,
"selected": false,
"text": "blah();\nif (5) {\n // do something\n}\n #include <iostream>\n#include <string>\n\nusing namespace std;\n\nstring blah()\n{\n return \"blah\";\n}\n\nbool operator,(const string& key, const int& val) {\n return false;\n}\n\nint main (int argc, char * const argv[]) {\n\n if (blah(), 5) {\n cout << \"if block\";\n } else {\n cout << \"else block\";\n }\n\n return 0;\n}\n"
},
{
"answer_id": 149533,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 0,
"selected": false,
"text": "blah();\n// do something\n"
},
{
"answer_id": 149594,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 4,
"selected": false,
"text": "class PlaceHolder\n{\n};\n\nPlaceHolder Blah() { return PlaceHolder(); }\n\nbool operator,(PlaceHolder, int) { return false; }\n\nif (Blah(), 5)\n{\n cout << \"This will never run.\";\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20630/"
] |
149,506
|
<p>I'm investigating an annotation-based approach to validating Spring beans using <a href="https://springmodules.dev.java.net/" rel="nofollow noreferrer">spring modules</a>. In <a href="http://wheelersoftware.com/articles/spring-bean-validation-framework.html" rel="nofollow noreferrer">this tutorial</a>, the following bean (getters and setters omitted) is used as an example:</p>
<pre><code>public final class User {
@NotBlank
@Length(max = 80)
private String name;
@NotBlank
@Email
@Length(max = 80)
private String email;
@NotBlank
@Length(max = 4000)
private String text;
}
</code></pre>
<p>The error message that is used if a particular validation rule is disobeyed should follow this format:</p>
<pre><code>bean-class.bean-propery[validation-rule]=Validation Error message
</code></pre>
<p>Examples for the class shown above include:</p>
<pre><code>User.email[not.blank]=Please enter your e-mail address.
User.email[email]=Please enter a valid e-mail address.
User.email[length]=Please enter no more than {2} characters.
</code></pre>
<p>The fact that the message keys contain the class name presents a couple of problems:</p>
<ol>
<li>If the class is renamed, the message keys also need to be changed</li>
<li><p>If I have another class (e.g. Person) with an email property that is validated identically to User.email, I need to duplicate the messages, e.g.</p>
<p>Person.email[not.blank]=Please enter your e-mail address.<br>
Person.email[email]=Please enter a valid e-mail address.<br>
Person.email[length]=Please enter no more than {2} characters.</p></li>
</ol>
<p>In fact, the documentation claims that is possible to configure a default message for a particular rule (e.g. @Email) like this:</p>
<pre><code>email=email address is invalid
</code></pre>
<p>This default message should be used if a bean-specific message for the rule cannot be found. However, my experience is that this simply does not work. </p>
<p>An alternative mechanism for avoiding duplicate messages is to pass the key of the error message to the rule annotation. For example, assume I have defined the following default error message for the @Email rule</p>
<pre><code>badEmail=Email address is invalid
</code></pre>
<p>This message should be used if I annotate the relevant property like this:</p>
<pre><code>@Email(errorCode="badEmail")
private String email;
</code></pre>
<p>However I tried this, out and again, it just doesn't seem to work. Has anyone found a way to avoid duplicating error messages when using this validation framework?</p>
|
[
{
"answer_id": 176039,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 4,
"selected": true,
"text": "....\n<bean id=\"validator\" class=\"org.springmodules.validation.bean.BeanValidator\"\n p:configurationLoader-ref=\"configurationLoader\"\n p:errorCodeConverter-ref=\"errorCodeConverter\" />\n\n<bean id=\"errorCodeConverter\" class=\"contact.MyErrorCodeConverter\" />\n....\n package contact;\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.springmodules.validation.bean.converter.ErrorCodeConverter;\n\npublic class MyErrorCodeConverter implements ErrorCodeConverter {\n\n private Log log = LogFactory.getLog(MyErrorCodeConverter.class);\n\n @Override\n public String convertPropertyErrorCode(String errorCode, Class clazz, String property) {\n log.error(String.format(\"Property %s %s %s\", errorCode, clazz.getClass().getName(), property));\n return errorCode; // <------ use the errorCode only\n }\n\n @Override\n public String convertGlobalErrorCode(String errorCode, Class clazz) {\n log.error(String.format(\"Global %s %s\", errorCode, clazz.getClass().getName()));\n return errorCode;\n }\n}\n MyEmailErrorCode=Bad email\n\nclass Foo {\n @Email(errorCode=\"MyEmailErrorCode\")\n String email\n}\n"
},
{
"answer_id": 39374697,
"author": "VHS",
"author_id": 5749570,
"author_profile": "https://Stackoverflow.com/users/5749570",
"pm_score": 0,
"selected": false,
"text": "applicationContext.xml <bean id=\"configurationLoader\"\n class=\"org.springmodules.validation.bean.conf.loader.annotation.AnnotationBeanValidationConfigurationLoader\" />\n\n<!-- Use the error codes as is. Don't convert them to <Bean class name>.<bean field being validated>[errorCode]. --> \n<bean id=\"errorCodeConverter\"\n class=\"org.springmodules.validation.bean.converter.KeepAsIsErrorCodeConverter\"/>\n\n <!-- shortCircuitFieldValidation = true ==> If the first rule fails on a field, no need to check \n other rules for that field --> \n<bean id=\"validator\" class=\"org.springmodules.validation.bean.BeanValidator\"\n p:configurationLoader-ref=\"configurationLoader\"\n p:shortCircuitFieldValidation=\"true\" \n p:errorCodeConverter-ref=\"errorCodeConverter\"/>\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
149,530
|
<p>I have code from an old website that I needed to modify. There are two pages that I modified some form code in. I modified the max length of a textbox and I modified slightly a line or two of code in a function. The "btnSubmit_Click" function as it happens.</p>
<p>With the new code FTPed up on the webserver, when I click on the "Submit" button using Firefox 3, the button does what it is supposed to do. With IE7, nothing happens. No page load, no refresh, no error, no nothing. IE isn't busy, it doesn't time out, it does nada.</p>
<p>On my development laptop however, when I run the project, the submit button works in IE7 as it is supposed to do. </p>
<p>Any thoughts?</p>
<p><strong>Response to Mecki:</strong>
It is method=POST, but it is a JavaScript postback thing alright. Also I checked the outputted HTML and the Submit button has a JS "onclick" event:<br>
onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); "</p>
<p>Absolutely though all the required fields have what they need. The validation also works as when I test it by leaving out info from a required field IE7 asks me to fill in the data. Strange one.</p>
|
[
{
"answer_id": 13083362,
"author": "A.D.K",
"author_id": 1742791,
"author_profile": "https://Stackoverflow.com/users/1742791",
"pm_score": 2,
"selected": false,
"text": "<form> <form>"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13980/"
] |
149,551
|
<p>We have a few operations where we are doing a large number of large string concatenations, and have recently encountered an out of memory exception. Unfortunately, debugging the code is not an option, as this is occurring at a customer site. </p>
<p>So, before looking into a overhaul of our code, I would like to ask: what is the RAM consumption characteristics of StringBuilder for large strings? </p>
<p>Especially as they compare to the standard string type. The size of the strings are well over 10 MB, and we seem to run into the issues around 20 MB.</p>
<p><strong>NOTE</strong>: This is not about speed but RAM.</p>
|
[
{
"answer_id": 149576,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": -1,
"selected": false,
"text": "string a = \"a\";\n\n//creates object with a\n\na += \"b\"\n\n/creates object with b, creates object with ab, assings object with ab to \"a\" pointer\n"
},
{
"answer_id": 149729,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 1,
"selected": false,
"text": "string output = \"Test\";\noutput += \", printed on \" + datePrinted.ToString();\noutput += \", verified by \" + verificationName;\noutput += \", number lines: \" + numberLines.ToString();\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13990/"
] |
149,569
|
<p>How do I write unit tests in .NET? </p>
<p>Specifically Visual Studio 2005?</p>
|
[
{
"answer_id": 212016,
"author": "Chris Burgess",
"author_id": 6624,
"author_profile": "https://Stackoverflow.com/users/6624",
"pm_score": 2,
"selected": false,
"text": "Imports nunit.Framework <TestFixture()> <TestFixture()> Public Class MyTestClass <Test()> <Test()> _\nPublic Sub harness()\n Assert.IsTrue(False)\nEnd Sub\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
149,570
|
<p>Has anyone ever done work to get Ruby to do continuations (like Seaside on Smalltalk)?</p>
|
[
{
"answer_id": 149699,
"author": "Krzysiek Goj",
"author_id": 23018,
"author_profile": "https://Stackoverflow.com/users/23018",
"pm_score": 5,
"selected": true,
"text": "callcc Generator"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23513/"
] |
149,573
|
<p>Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected.</p>
<p>(The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :)</p>
|
[
{
"answer_id": 149592,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 2,
"selected": false,
"text": "select"
},
{
"answer_id": 149620,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": false,
"text": "var foo = document.getElementById('yourSelect');\nif (foo)\n{\n if (foo.selectedIndex != null)\n {\n foo.selectedIndex = 0;\n } \n}\n"
},
{
"answer_id": 149820,
"author": "Joe Lencioni",
"author_id": 18986,
"author_profile": "https://Stackoverflow.com/users/18986",
"pm_score": 9,
"selected": true,
"text": "<select id=\"mySelect\" multiple=\"multiple\">\n <option value=\"1\">First</option>\n <option value=\"2\">Second</option>\n <option value=\"3\">Third</option>\n <option value=\"4\">Fourth</option>\n</select>\n\n<script type=\"text/javascript\"> \n$(document).ready(function() {\n if (!$(\"#mySelect option:selected\").length) {\n $(\"#mySelect option[value='3']\").attr('selected', 'selected');\n }\n});\n</script>\n"
},
{
"answer_id": 149861,
"author": "Alexander Pendleton",
"author_id": 21201,
"author_profile": "https://Stackoverflow.com/users/21201",
"pm_score": 4,
"selected": false,
"text": "('#mySelect option:last') #mySelect option[value='yourDefaultValue']"
},
{
"answer_id": 149934,
"author": "meleyal",
"author_id": 4196,
"author_profile": "https://Stackoverflow.com/users/4196",
"pm_score": 2,
"selected": false,
"text": "$(document).ready(function(){\n if ( $(\"#context\").selectedValues() == false) {\n $(\"#context\").selectOptions(\"71\");\n }\n});\n"
},
{
"answer_id": 1649507,
"author": "sata",
"author_id": 199630,
"author_profile": "https://Stackoverflow.com/users/199630",
"pm_score": 3,
"selected": false,
"text": "function selectOption(select_id, option_val) {\n $('#'+select_id+' option:selected').removeAttr('selected');\n $('#'+select_id+' option[value='+option_val+']').attr('selected','selected'); \n}\n"
},
{
"answer_id": 1652471,
"author": "Joel",
"author_id": 199941,
"author_profile": "https://Stackoverflow.com/users/199941",
"pm_score": 2,
"selected": false,
"text": "$(\".Result\").html($(\"option:selected\").text());\n"
},
{
"answer_id": 1847923,
"author": "giagejoe",
"author_id": 214993,
"author_profile": "https://Stackoverflow.com/users/214993",
"pm_score": 1,
"selected": false,
"text": "$(\"#mySelect\").val( 3 );\n"
},
{
"answer_id": 1873462,
"author": "Ram Prasad",
"author_id": 186923,
"author_profile": "https://Stackoverflow.com/users/186923",
"pm_score": 3,
"selected": false,
"text": "<script type=\"text/javascript\"> \n$(document).ready(function() {\n if (!$(\"#mySelect option:selected\").length)\n $(\"#mySelect\").val( 3 );\n\n});\n</script>\n"
},
{
"answer_id": 3487319,
"author": "user420944",
"author_id": 420944,
"author_profile": "https://Stackoverflow.com/users/420944",
"pm_score": 0,
"selected": false,
"text": "$(\"option[value*='2']\").attr('selected', 'selected');\n// 2 for example, add * for every option\n"
},
{
"answer_id": 9972446,
"author": "Taimoor Changaiz",
"author_id": 1222852,
"author_profile": "https://Stackoverflow.com/users/1222852",
"pm_score": 0,
"selected": false,
"text": "$(\"#select_box_id\").children()[1].selected\n"
},
{
"answer_id": 18354158,
"author": "Avinash Saini",
"author_id": 2226601,
"author_profile": "https://Stackoverflow.com/users/2226601",
"pm_score": 1,
"selected": false,
"text": "if (!$(\"#select\").find(\"option:selected\").length){\n //\n}\n"
},
{
"answer_id": 18793799,
"author": "Gavin",
"author_id": 2211053,
"author_profile": "https://Stackoverflow.com/users/2211053",
"pm_score": 4,
"selected": false,
"text": "if ($('#mySelect option:selected').length > 0) { alert('has a selected item'); }\n if ($('#mySelect option:selected').length == 0) { alert('nothing selected'); }\n $('#mySelect option').each(function() {\n if ($(this).is(':selected')) { .. }\n});\n $('#mySelect option').each(function() {\n if ($(this).not(':selected')) { .. }\n});\n"
},
{
"answer_id": 21787851,
"author": "Akash Deep Singhal",
"author_id": 2791794,
"author_profile": "https://Stackoverflow.com/users/2791794",
"pm_score": 0,
"selected": false,
"text": "$(\"#type\").change(function(){\n var id = $(this).find(\"option:selected\").attr(\"id\");\n\n switch (id){\n case \"trade_buy_max\":\n // do something here\n break;\n }\n});\n"
},
{
"answer_id": 23229044,
"author": "Steven Schoch",
"author_id": 2548668,
"author_profile": "https://Stackoverflow.com/users/2548668",
"pm_score": 0,
"selected": false,
"text": "$('.mySelect:not(:has(option[selected])) option[value=\"2\"]').attr('selected', true);\n :selected [selected]"
},
{
"answer_id": 29184991,
"author": "Marcin Bąk",
"author_id": 4697638,
"author_profile": "https://Stackoverflow.com/users/4697638",
"pm_score": 1,
"selected": false,
"text": " if(!$('#some_select option[selected=\"selected\"]').val()) {\n //here code if it HAS NOT selected value\n //for exaple adding the first value as \"placeholder\"\n $('#some_select option:first-child').before('<option disabled selected>Wybierz:</option>');\n }\n"
},
{
"answer_id": 34836842,
"author": "zeman",
"author_id": 1994491,
"author_profile": "https://Stackoverflow.com/users/1994491",
"pm_score": 0,
"selected": false,
"text": "option:selected var viewport_selected = false; \n$('#viewport option').each(function() {\n if ($(this).attr(\"selected\") == \"selected\") {\n viewport_selected = true;\n }\n});\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196/"
] |
149,577
|
<p>My math-fu is failing me! I need an efficient way of reducing network ranges to supersets, e.g. if I input list of IP ranges:</p>
<ul>
<li>1.1.1.1 to 2.2.2.5</li>
<li>1.1.1.2 to 2.2.2.4</li>
<li>10.5.5.5 to 155.5.5.5</li>
<li>10.5.5.6 to 10.5.5.7</li>
</ul>
<p>I want to return the following ranges:</p>
<ul>
<li>1.1.1.1 to 2.2.2.5</li>
<li>10.5.5.5 to 155.5.5.5</li>
</ul>
<p>Note: the input lists are not ordered (though they could be?). The naive way to do this is to check every range in the list to see if the input range x is a subset, and if so, NOT insert range x. However, whenever you insert a new range it might be a superset of existing ranges, so you have to check the existing ranges to see if they can be collapsed (e.g., removed from my list).</p>
|
[
{
"answer_id": 152594,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 3,
"selected": false,
"text": "1.1.1.1 to 2.2.2.5\n1.1.1.2 to 2.2.2.4\n 16,843,009 to 33,686,021\n16,843,010 to 33,686,020\n startIP2 >= startIP1 && startIP2 <= endIP1 &&\nendIP1 >= startIP1 && endIP2 <= endIP1\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12979/"
] |
149,585
|
<p>Does BeautifulSoup work with Python 3? </p>
<p>If not, how soon will there be a port? Will there be a port at all?</p>
<p>Google doesn't turn up anything to me (Maybe it's 'coz I'm looking for the wrong thing?)</p>
|
[
{
"answer_id": 9906160,
"author": "badp",
"author_id": 13992,
"author_profile": "https://Stackoverflow.com/users/13992",
"pm_score": 4,
"selected": false,
"text": "pip install beautifulsoup4\n"
},
{
"answer_id": 51483060,
"author": "Tanvir Islam Streame",
"author_id": 5740655,
"author_profile": "https://Stackoverflow.com/users/5740655",
"pm_score": 0,
"selected": false,
"text": "apt-get install python3-bs4 \n pip install beautifulsoup4\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17865/"
] |
149,600
|
<p>Do you know any good tools for nicely formatting messy php code? Preferably a script for Aptana/Eclipse, but a standalone tool will do too.</p>
|
[
{
"answer_id": 150028,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 5,
"selected": true,
"text": "if($code == BAD){$action = REWRITE;}else{$action = KEEP;}\nfor($i=0; $i<10;$i++){while($j>0){$j++;doCall($i+$j);if($k){$k/=10;}}}\n if ($code == BAD) {\n $action = REWRITE;\n} else {\n $action = KEEP;\n}\nfor($i = 0; $i < 10;$i++) {\n while ($j > 0) {\n $j++;\n doCall($i + $j);\n if ($k) {\n $k /= 10;\n }\n }\n}\n"
},
{
"answer_id": 494295,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 5,
"selected": false,
"text": "#!/usr/bin/php\n<?php\nclass Token {\n public $type;\n public $contents;\n\n public function __construct($rawToken) {\n if (is_array($rawToken)) {\n $this->type = $rawToken[0];\n $this->contents = $rawToken[1];\n } else {\n $this->type = -1;\n $this->contents = $rawToken;\n }\n }\n}\n\n$file = $argv[1];\n$code = file_get_contents($file);\n\n$rawTokens = token_get_all($code);\n$tokens = array();\nforeach ($rawTokens as $rawToken) {\n $tokens[] = new Token($rawToken);\n}\n\nfunction skipWhitespace(&$tokens, &$i) {\n global $lineNo;\n $i++;\n $token = $tokens[$i];\n while ($token->type == T_WHITESPACE) {\n $lineNo += substr($token->contents, \"\\n\");\n $i++;\n $token = $tokens[$i];\n }\n}\n\nfunction nextToken(&$j) {\n global $tokens, $i;\n $j = $i;\n do {\n $j++;\n $token = $tokens[$j];\n } while ($token->type == T_WHITESPACE);\n return $token;\n}\n\n$OPERATORS = array('=', '.', '+', '-', '*', '/', '%', '||', '&&', '+=', '-=', '*=', '/=', '.=', '%=', '==', '!=', '<=', '>=', '<', '>', '===', '!==');\n\n$IMPORT_STATEMENTS = array(T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE);\n\n$CONTROL_STRUCTURES = array(T_IF, T_ELSEIF, T_FOREACH, T_FOR, T_WHILE, T_SWITCH, T_ELSE);\n$WHITESPACE_BEFORE = array('?', '{', '=>');\n$WHITESPACE_AFTER = array(',', '?', '=>');\n\nforeach ($OPERATORS as $op) {\n $WHITESPACE_BEFORE[] = $op;\n $WHITESPACE_AFTER[] = $op;\n}\n\n$matchingTernary = false;\n\n// First pass - filter out unwanted tokens\n$filteredTokens = array();\nfor ($i = 0, $n = count($tokens); $i < $n; $i++) {\n $token = $tokens[$i];\n if ($token->contents == '?') {\n $matchingTernary = true;\n }\n if (in_array($token->type, $IMPORT_STATEMENTS) && nextToken($j)->contents == '(') {\n $filteredTokens[] = $token;\n if ($tokens[$i + 1]->type != T_WHITESPACE) {\n $filteredTokens[] = new Token(array(T_WHITESPACE, ' '));\n }\n $i = $j;\n do {\n $i++;\n $token = $tokens[$i];\n if ($token->contents != ')') {\n $filteredTokens[] = $token;\n }\n } while ($token->contents != ')');\n } elseif ($token->type == T_ELSE && nextToken($j)->type == T_IF) {\n $i = $j;\n $filteredTokens[] = new Token(array(T_ELSEIF, 'elseif'));\n } elseif ($token->contents == ':') {\n if ($matchingTernary) {\n $matchingTernary = false;\n } elseif ($tokens[$i - 1]->type == T_WHITESPACE) {\n array_pop($filteredTokens); // Remove whitespace before\n }\n $filteredTokens[] = $token;\n } else {\n $filteredTokens[] = $token;\n }\n}\n$tokens = $filteredTokens;\n\nfunction isAssocArrayVariable($offset = 0) {\n global $tokens, $i;\n $j = $i + $offset;\n return $tokens[$j]->type == T_VARIABLE &&\n $tokens[$j + 1]->contents == '[' &&\n $tokens[$j + 2]->type == T_STRING &&\n preg_match('/[a-z_]+/', $tokens[$j + 2]->contents) &&\n $tokens[$j + 3]->contents == ']';\n}\n\n// Second pass - add whitespace\n$matchingTernary = false;\n$doubleQuote = false;\nfor ($i = 0, $n = count($tokens); $i < $n; $i++) {\n $token = $tokens[$i];\n if ($token->contents == '?') {\n $matchingTernary = true;\n }\n if ($token->contents == '\"' && isAssocArrayVariable(1) && $tokens[$i + 5]->contents == '\"') {\n /*\n * Handle case where the only thing quoted is the assoc array variable.\n * Eg. \"$value[key]\"\n */\n $quote = $tokens[$i++]->contents;\n $var = $tokens[$i++]->contents;\n $openSquareBracket = $tokens[$i++]->contents;\n $str = $tokens[$i++]->contents;\n $closeSquareBracket = $tokens[$i++]->contents;\n $quote = $tokens[$i]->contents; \n echo $var . \"['\" . $str . \"']\";\n $doubleQuote = false;\n continue;\n }\n if ($token->contents == '\"') {\n $doubleQuote = !$doubleQuote;\n }\n if ($doubleQuote && $token->contents == '\"' && isAssocArrayVariable(1)) {\n // don't echo \"\n } elseif ($doubleQuote && isAssocArrayVariable()) {\n if ($tokens[$i - 1]->contents != '\"') {\n echo '\" . ';\n }\n $var = $token->contents;\n $openSquareBracket = $tokens[++$i]->contents;\n $str = $tokens[++$i]->contents;\n $closeSquareBracket = $tokens[++$i]->contents;\n echo $var . \"['\" . $str . \"']\";\n if ($tokens[$i + 1]->contents != '\"') {\n echo ' . \"';\n } else {\n $i++; // process \"\n $doubleQuote = false;\n }\n } elseif ($token->type == T_STRING && $tokens[$i - 1]->contents == '[' && $tokens[$i + 1]->contents == ']') {\n if (preg_match('/[a-z_]+/', $token->contents)) {\n echo \"'\" . $token->contents . \"'\";\n } else {\n echo $token->contents;\n }\n } elseif ($token->type == T_ENCAPSED_AND_WHITESPACE || $token->type == T_STRING) {\n echo $token->contents;\n } elseif ($token->contents == '-' && in_array($tokens[$i + 1]->type, array(T_LNUMBER, T_DNUMBER))) {\n echo '-';\n } elseif (in_array($token->type, $CONTROL_STRUCTURES)) {\n echo $token->contents;\n if ($tokens[$i + 1]->type != T_WHITESPACE) {\n echo ' ';\n }\n } elseif ($token->contents == '}' && in_array($tokens[$i + 1]->type, $CONTROL_STRUCTURES)) {\n echo '} ';\n } elseif ($token->contents == '=' && $tokens[$i + 1]->contents == '&') {\n if ($tokens[$i - 1]->type != T_WHITESPACE) {\n echo ' ';\n }\n $i++; // match &\n echo '=&';\n if ($tokens[$i + 1]->type != T_WHITESPACE) {\n echo ' '; \n }\n } elseif ($token->contents == ':' && $matchingTernary) {\n $matchingTernary = false;\n if ($tokens[$i - 1]->type != T_WHITESPACE) {\n echo ' ';\n }\n echo ':';\n if ($tokens[$i + 1]->type != T_WHITESPACE) {\n echo ' ';\n }\n } elseif (in_array($token->contents, $WHITESPACE_BEFORE) && $tokens[$i - 1]->type != T_WHITESPACE &&\n in_array($token->contents, $WHITESPACE_AFTER) && $tokens[$i + 1]->type != T_WHITESPACE) {\n echo ' ' . $token->contents . ' ';\n } elseif (in_array($token->contents, $WHITESPACE_BEFORE) && $tokens[$i - 1]->type != T_WHITESPACE) {\n echo ' ' . $token->contents;\n } elseif (in_array($token->contents, $WHITESPACE_AFTER) && $tokens[$i + 1]->type != T_WHITESPACE) {\n echo $token->contents . ' ';\n } else {\n echo $token->contents;\n }\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556/"
] |
149,609
|
<p>Does the using catch the exception or throw it? i.e. </p>
<pre><code>using (StreamReader rdr = File.OpenText("file.txt"))
{
//do stuff
}
</code></pre>
<p>If the streamreader throws an exception is it caught by using or thrown so the calling function can handle it?</p>
|
[
{
"answer_id": 149625,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 4,
"selected": false,
"text": "using IDisposable"
},
{
"answer_id": 149643,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 6,
"selected": false,
"text": "StreadReader rdr = null;\ntry\n{\n rdr = File.OpenText(\"file.txt\");\n //do stuff\n}\nfinally\n{\n if (rdr != null)\n rdr.Dispose();\n}\n"
},
{
"answer_id": 149649,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 3,
"selected": false,
"text": "try\n{\n using (\n StreamReader rdr = File.OpenText(\"file.txt\"))\n { //do stuff \n }\n}\ncatch (FileNotFoundException Ex)\n{\n // The file didn't exist\n}\ncatch (AccessViolationException Ex)\n{\n // You don't have the permission to open this\n}\ncatch (Exception Ex)\n{\n // Something happened! \n}\n"
},
{
"answer_id": 149657,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "using using"
},
{
"answer_id": 5878360,
"author": "Branko Dimitrijevic",
"author_id": 533120,
"author_profile": "https://Stackoverflow.com/users/533120",
"pm_score": 2,
"selected": false,
"text": "File.OpenText Dispose //do stuff Dispose"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21299/"
] |
149,617
|
<p>Let's assume that I have some packets with a 16-bit checksum at the end. I would like to guess which checksum algorithm is used.</p>
<p>For a start, from dump data I can see that one byte change in the packet's payload totally changes the checksum, so I can assume that it isn't some kind of simple XOR or sum.</p>
<p>Then I tried <a href="http://svn.rot13.org/index.cgi/RFID/view/guess-crc.pl" rel="noreferrer">several variations of CRC16</a>, but without much luck.</p>
<p>This question might be more biased towards cryptography, but I'm really interested in any easy to understand statistical tools to find out which CRC this might be. I might even turn to <a href="http://lcamtuf.coredump.cx/newtcp/" rel="noreferrer">drawing different CRC algorithms</a> if everything else fails.</p>
<p>Backgroud story: I have serial RFID protocol with some kind of checksum. I can replay messages without problem, and interpret results (without checksum check), but I can't send modified packets because device drops them on the floor. </p>
<p>Using existing software, I can change payload of RFID chip. However, unique serial number is immutable, so I don't have ability to check every possible combination. Allthough I could generate dumps of values incrementing by one, but not enough to make exhaustive search applicable to this problem.</p>
<p><a href="http://www.bljak.org/~dpavlin/rfid-serial-dump.tar.gz" rel="noreferrer">dump files with data</a> are available if question itself isn't enough :-)</p>
<p><strong>Need reference documentation?</strong> <a href="http://www.geocities.com/SiliconValley/Pines/8659/crc.htm" rel="noreferrer">A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS</a> is great reference which I found after asking question here.</p>
<p>In the end, after very helpful hint in accepted answer than it's CCITT, I
<a href="http://www.zorc.breitbandkatze.de/crc.html" rel="noreferrer">used this CRC calculator</a>, and xored generated checksum with known checksum to get 0xffff which led me to conclusion that final xor is 0xffff instread of CCITT's 0x0000.</p>
|
[
{
"answer_id": 158693,
"author": "selwyn",
"author_id": 16314,
"author_profile": "https://Stackoverflow.com/users/16314",
"pm_score": 5,
"selected": true,
"text": "Polynomial\nNo of bits (16 or 32)\nNormal (LSB first) or Reverse (MSB first)\nInitial value\nHow the final value is manipulated (e.g. subtracted from 0xffff), or is a constant value\n LRC: Polynomial=0x81; 8 bits; Normal; Initial=0; Final=as calculated\nCRC16: Polynomial=0xa001; 16 bits; Normal; Initial=0; Final=as calculated\nCCITT: Polynomial=0x1021; 16 bits; reverse; Initial=0xffff; Final=0x1d0f\nXmodem: Polynomial=0x1021; 16 bits; reverse; Initial=0; Final=0x1d0f\nCRC32: Polynomial=0xebd88320; 32 bits; Normal; Initial=0xffffffff; Final=inverted value\nZIP32: Polynomial=0x04c11db7; 32 bits; Normal; Initial=0xffffffff; Final=as calculated\n IPX: Polynomial=0x8005; 16 bits; Reverse; Initial=0xffff; Final=as calculated\nISO 18000-6B: Polynomial=0x1021; 16 bits; Reverse; Initial=0xffff; Final=as calculated\nISO 18000-6C: Polynomial=0x1021; 16 bits; Reverse; Initial=0xffff; Final=as calculated\n Data must be padded with zeroes to make a multiple of 8 bits\nISO CRC5: Polynomial=custom; 5 bits; Reverse; Initial=0x9; Final=shifted left by 3 bits\n Data must be padded with zeroes to make a multiple of 8 bits\nEPC class 1: Polynomial=custom 0x1021; 16 bits; Reverse; Initial=0xffff; Final=post processing of 16 zero bits\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1081/"
] |
149,627
|
<p>Is there a clean way of cloning a record in SQL that has an index(auto increment). I want to clone all the fields except the index. I currently have to enumerate every field, and use that in an insert select, and I would rather not explicitly list all of the fields, as they may change over time.</p>
|
[
{
"answer_id": 149650,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 2,
"selected": true,
"text": "-- Get list of columns in table\nSELECT INTO #t\nEXEC sp_columns @table_name = N'TargetTable'\n\n-- Create a comma-delimited string excluding the identity column\nDECLARE @cols varchar(MAX)\nSELECT @cols = COALESCE(@cols+',' ,'') + COLUMN_NAME FROM #t WHERE COLUMN_NAME <> 'id'\n\n-- Construct dynamic SQL statement\nDECLARE @sql varchar(MAX)\nSET @sql = 'INSERT INTO TargetTable (' + @cols + ') ' +\n 'SELECT ' + @cols + ' FROM TargetTable WHERE SomeCondition'\n\nPRINT @sql -- for debugging\nEXEC(@sql)\n"
},
{
"answer_id": 149785,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 0,
"selected": false,
"text": "if (CURRENT_ROLE = 'CLONE') then\n new.ID = assign new id from generator/sequence\n"
},
{
"answer_id": 2437212,
"author": "Danny",
"author_id": 292794,
"author_profile": "https://Stackoverflow.com/users/292794",
"pm_score": 1,
"selected": false,
"text": "DROP TABLE #tmp_MyTable\n\nSELECT * INTO #tmp_MyTable\nFROM MyTable\nWHERE MyIndentID = 165\n\nALTER TABLE #tmp_MyTable\nDROP Column MyIndentID\n\nINSERT INTO MyTable\nSELECT * \nFROM #tmp_MyTable\n"
},
{
"answer_id": 9830110,
"author": "Marie",
"author_id": 1286924,
"author_profile": "https://Stackoverflow.com/users/1286924",
"pm_score": 1,
"selected": false,
"text": "CREATE TEMPORARY TABLE projecttemp SELECT * FROM project WHERE projectid='6';\nALTER TABLE projecttemp DROP COLUMN projectid;\nUPDATE projecttemp SET projectnum = CONCAT(projectnum, ' CLONED');\nINSERT INTO project SELECT NULL,projecttemp.* FROM projecttemp;\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17712/"
] |
149,635
|
<p>I've got some JSON data, but it's all on one line. Does anyone know of a web or Windows editor that will format (e.g. indent and insert new lines) this data for me, so I can read it better? Preferably one that uses a GUI to display the JSON—instead of a command-line tool that outputs a reformatted document, for example.</p>
|
[
{
"answer_id": 7059746,
"author": "Nick Perkins",
"author_id": 138939,
"author_profile": "https://Stackoverflow.com/users/138939",
"pm_score": 0,
"selected": false,
"text": "{} x={}; x= ; function get_json_file(url,options,callback){\n var opts = {dataType:\"text\"};\n opts.url = url;\n $.extend(opts,options);\n opts.success=function(data){\n var json = data.substring(data.indexOf('{'),data.lastIndexOf('}')+1);\n var obj = JSON.parse(json);\n callback(obj);\n };\n $.ajax(opts);\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11574/"
] |
149,639
|
<p>I've got a 'task list' database that uses the adjacency list model (see below) so each 'task' can have unlimited sub-tasks. The table has an 'TaskOrder' column so everything renders in the correct order on a treeview.</p>
<p>Is there an SQL statement (MS-SQL 2005) that will select all the child nodes for a specified parent and update the TaskOder column when a sibling is deleted?</p>
<pre>
Task Table
----------
TaskId
ParentTaskId
TaskOrder
TaskName
--etc--
</pre>
<p>Any ideas? Thanks.</p>
|
[
{
"answer_id": 149711,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "DECLARE @Tasks TABLE\n(\n TaskId int PRIMARY KEY,\n ParentTaskId int,\n TaskOrder int,\n TaskName varchar(30)\n)\n\nINSERT INTO @Tasks(TaskId, ParentTaskId, TaskOrder, TaskName)\nSELECT 1, null, 1, 'ParentTask'\n\nINSERT INTO @Tasks(TaskId, ParentTaskId, TaskOrder, TaskName)\nSELECT 2, 1, 2, 'B'\n\nINSERT INTO @Tasks(TaskId, ParentTaskId, TaskOrder, TaskName)\nSELECT 3, 1, 1, 'A'\n\nINSERT INTO @Tasks(TaskId, ParentTaskId, TaskOrder, TaskName)\nSELECT 4, 1, 3, 'C'\n--Initial\nSELECT * FROM @Tasks WHERE ParentTaskId = 1 ORDER BY TaskOrder\n\nDELETE FROM @Tasks WHERE TaskId = 2\n--After Delete\nSELECT * FROM @Tasks WHERE ParentTaskId = 1 ORDER BY TaskOrder\n\n\nUPDATE t\nSET TaskOrder = NewTaskOrder\nFROM @Tasks t\n JOIN\n(\nSELECT TaskId, ROW_Number() OVER(ORDER BY TaskOrder) as NewTaskOrder\nFROM @Tasks\nWHERE ParentTaskId = 1\n) sub ON t.TaskId = sub.TaskId\n\n--After Update\nSELECT * FROM @Tasks WHERE ParentTaskId = 1 ORDER BY TaskOrder\n"
},
{
"answer_id": 149713,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 0,
"selected": false,
"text": "UPDATE TaskTable\nSET ParentTaskID = (SELECT ParentTaskID AS temp FROM Task_Table t1 WHERE TaskID = 88)\nWHERE\nTaskID IN (SELECT TaskID task2 FROM TaskTable t2 WHERE ParentTaskID = 88);\nDelete FROM TaskTable WHERE TaskID = 88;\n"
},
{
"answer_id": 150920,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 2,
"selected": true,
"text": "CREATE TRIGGER ON yourtable FOR DELETE\nAS\n UPDATE Task\n SET TaskOrder = TaskOrder - 1\n WHERE ParentTaskId = deleted.ParentTaskId\n AND TaskOrder > deleted.TaskOrder\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072/"
] |
149,646
|
<p>In the Apple documentation for <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html#//apple_ref/occ/instm/NSRunLoop/run" rel="noreferrer">NSRunLoop</a> there is sample code demonstrating suspending execution while waiting for a flag to be set by something else.</p>
<pre><code>BOOL shouldKeepRunning = YES; // global
NSRunLoop *theRL = [NSRunLoop currentRunLoop];
while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
</code></pre>
<p>I have been using this and it works but in investigating a performance issue I tracked it down to this piece of code. I use almost exactly the same piece of code (just the name of the flag is different :) and if I put a <code>NSLog</code> on the line after the flag is being set (in another method) and then a line after the <code>while()</code> there is a seemingly random wait between the two log statements of several seconds.</p>
<p>The delay does not seem to be different on slower or faster machines but does vary from run to run being at least a couple of seconds and up to 10 seconds.</p>
<p>I have worked around this issue with the following code but it does not seem right that the original code doesn't work.</p>
<pre><code>NSDate *loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];
while (webViewIsLoading && [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:loopUntil])
loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];
</code></pre>
<p>using this code, the log statements when setting the flag and after the while loop are now consistently less than 0.1 seconds apart.</p>
<p>Anyone any ideas why the original code exhibits this behaviour?</p>
|
[
{
"answer_id": 150417,
"author": "Jon Shea",
"author_id": 3770,
"author_profile": "https://Stackoverflow.com/users/3770",
"pm_score": 2,
"selected": false,
"text": "NSRunLoops runMode:beforeDate: NSRunLoop runMode:beforeDate: runMode:beforeDate: while() shouldKeepRunning NO runMode:beforeDate:"
},
{
"answer_id": 151500,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 3,
"selected": false,
"text": "-[NSRunLoop performSelector:target:argument:order:modes:"
},
{
"answer_id": 178083,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 4,
"selected": false,
"text": "@implementation MyWindowController\n\nvolatile BOOL pageStillLoading;\n\n- (void) runInBackground:(id)arg\n{\n NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n\n // Simmulate web page loading\n sleep(5);\n\n // This will not wake up the runloop on main thread!\n pageStillLoading = NO;\n\n // Wake up the main thread from the runloop\n [self performSelectorOnMainThread:@selector(wakeUpMainThreadRunloop:) withObject:nil waitUntilDone:NO];\n\n [pool release];\n}\n\n\n- (void) wakeUpMainThreadRunloop:(id)arg\n{\n // This method is executed on main thread!\n // It doesn't need to do anything actually, just having it run will\n // make sure the main thread stops running the runloop\n}\n\n\n- (IBAction)start:(id)sender\n{\n pageStillLoading = YES;\n [NSThread detachNewThreadSelector:@selector(runInBackground:) toTarget:self withObject:nil];\n [progress setHidden:NO];\n while (pageStillLoading) {\n [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];\n }\n [progress setHidden:YES];\n}\n\n@end\n"
},
{
"answer_id": 237152,
"author": "Wil Shipley",
"author_id": 30602,
"author_profile": "https://Stackoverflow.com/users/30602",
"pm_score": 4,
"selected": false,
"text": "- (IBAction)start:(id)sender\n{\n pageStillLoading = YES;\n [NSThread detachNewThreadSelector:@selector(runInBackground:) toTarget:self withObject:nil];\n [progress setHidden:NO];\n}\n\n- (void)wakeUpMainThreadRunloop:(id)arg\n{\n [progress setHidden:YES];\n}\n"
},
{
"answer_id": 18221959,
"author": "Richard",
"author_id": 1640726,
"author_profile": "https://Stackoverflow.com/users/1640726",
"pm_score": 1,
"selected": false,
"text": "BOOL shouldKeepRunning = YES; // global\nNSRunLoop *theRL = [NSRunLoop currentRunLoop];\nwhile (shouldKeepRunning && [theRL runMode:NSRunLoopCommonModes beforeDate:[NSDate distantFuture]]);\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4496/"
] |
149,690
|
<p>I am trying to extract a certain part of a column that is between delimiters.</p>
<p>e.g. find foo in the following</p>
<p>test 'esf :foo: bar</p>
<p>So in the above I'd want to return foo, but all the regexp functions only return true|false,
is there a way to do this in MySQL</p>
|
[
{
"answer_id": 149703,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 2,
"selected": false,
"text": "MID( fooField, LOCATE('foo', fooField), 3);\n"
},
{
"answer_id": 149756,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "select mid(col from locate(':',col) + 1 for \nlocate(':',col,locate(':',col)+1)-locate(':',col) - 1 ) \nfrom table where col rlike ':.*:';\n"
},
{
"answer_id": 149770,
"author": "Pete Karl II",
"author_id": 22491,
"author_profile": "https://Stackoverflow.com/users/22491",
"pm_score": 6,
"selected": true,
"text": "SELECT \n SUBSTR(column, \n LOCATE(':',column)+1, \n (CHAR_LENGTH(column) - LOCATE(':',REVERSE(column)) - LOCATE(':',column))) \nFROM table\n"
},
{
"answer_id": 149791,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 1,
"selected": false,
"text": "SUBSTR(\n SUBSTR(fooField,LOCATE(':',fooField)+1),\n 1,\n LOCATE(':',SUBSTR(fooField,LOCATE(':',fooField)+1))-1\n )\n"
},
{
"answer_id": 149816,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 0,
"selected": false,
"text": "$colNumber = 2; //2nd position\n$sql = \"REPLACE(SUBSTRING(SUBSTRING_INDEX(fooField, ':', $colNumber),\n LENGTH(SUBSTRING_INDEX(fooField, \n ':', \n $colNumber - 1)) + 1)\";\n"
},
{
"answer_id": 23839571,
"author": "chris2k",
"author_id": 2854900,
"author_profile": "https://Stackoverflow.com/users/2854900",
"pm_score": -1,
"selected": false,
"text": "testtable**"
},
{
"answer_id": 26789184,
"author": "Danny Z",
"author_id": 4224550,
"author_profile": "https://Stackoverflow.com/users/4224550",
"pm_score": 3,
"selected": false,
"text": "substring_index(substring_index(column,':',-2),':',1)\n"
},
{
"answer_id": 28712538,
"author": "hrushikesh",
"author_id": 1492552,
"author_profile": "https://Stackoverflow.com/users/1492552",
"pm_score": 1,
"selected": false,
"text": "mid(col, \n locate('?m=',col) + char_length('?m='), \n locate('&o=',col) - locate('?m=',col) - char_length('?m=') \n)\n char_length(.) 3 mid(col, locate('?m=',col) + 3, locate('&o=',col) - locate('?m=',col) - 3)\n '?m=' '&o'"
},
{
"answer_id": 39865512,
"author": "brewmanz",
"author_id": 2821586,
"author_profile": "https://Stackoverflow.com/users/2821586",
"pm_score": 0,
"selected": false,
"text": "23856.409:0023:trace:message:SPY_EnterMessage (0x2003a) L\"{#32769}\" [0081] WM_NCCREATE sent from self wp=00000000 lp=0023f0b0\n select \ntime('2000-01-01 00:00:00' + interval substring_index(theline255, '.', 1) second) as hhmmss\n, substring_index(substring_index(theline255, ':', 1), '.', -1) as logMilli\n, substring_index(substring_index(theline255, ':', 2), ':', -1) as logTid\n, substring_index(substring_index(theline255, ':', 3), ':', -1) as logType\n, substring_index(substring_index(theline255, ':', 4), ':', -1) as logArea\n, substring_index(substring_index(theline255, ' ', 1), ':', -1) as logFunction\n, substring(theline255, length(substring_index(theline255, ' ', 1)) + 2) as logText\nfrom loaddata255\n # LogTime, LogTimeMilli, LogTid, LogType, LogArea, LogFunction, LogText\n'06:37:36', '409', '0023', 'trace', 'message', 'SPY_EnterMessage', '(0x2003a) L\\\"{#32769}\\\" [0081] WM_NCCREATE sent from self wp=00000000 lp=0023f0b0'\n"
},
{
"answer_id": 44822505,
"author": "mprot",
"author_id": 7974700,
"author_profile": "https://Stackoverflow.com/users/7974700",
"pm_score": 0,
"selected": false,
"text": "select\n reverse(\n substring_index(\n reverse(substring_index(str,separator,substrindex)),\n separator,\n 1)\n );\n select\n reverse(\n substring_index(\n reverse(substring_index('www.mysql.com','.',2)),\n '.',\n 1\n )\n );\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
149,710
|
<p>In a C++ Linux app, what is the simplest way to get the functionality that the <a href="http://msdn.microsoft.com/en-us/library/system.threading.interlocked.aspx" rel="noreferrer">Interlocked</a> functions on Win32 provide? Specifically, a lightweight way to atomically increment or add 32 or 64 bit integers? </p>
|
[
{
"answer_id": 332214,
"author": "Ben Combee",
"author_id": 1323,
"author_profile": "https://Stackoverflow.com/users/1323",
"pm_score": 2,
"selected": false,
"text": "g_atomic"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23524/"
] |
149,718
|
<p>I have several .NET <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="nofollow noreferrer">Windows Forms</a> applications that I'm preparing to convert into a <a href="http://en.wikipedia.org/wiki/ClickOnce" rel="nofollow noreferrer">ClickOnce</a>/smart-client deployment scenario. I've read the isn't-this-great tutorials, but are there pitfalls or "gotchas" that I should be aware of?</p>
<p>There are several minor applications used off and on, but the main application is in C#, runs 24/7, is quite large, but only changes every few weeks. It also writes to a log file locallly and talks to local hardware devices.</p>
|
[
{
"answer_id": 542030,
"author": "Jamie Ide",
"author_id": 12752,
"author_profile": "https://Stackoverflow.com/users/12752",
"pm_score": 2,
"selected": false,
"text": "try\n{\n string company = string.Empty;\n string product = string.Empty;\n if (Attribute.IsDefined(asm, typeof(AssemblyCompanyAttribute)))\n {\n AssemblyCompanyAttribute asCompany = (AssemblyCompanyAttribute)Attribute.GetCustomAttribute(asm, typeof(AssemblyCompanyAttribute));\n company = asCompany.Company;\n }\n if (Attribute.IsDefined(asm, typeof(AssemblyProductAttribute)))\n {\n AssemblyProductAttribute asProduct = (AssemblyProductAttribute)Attribute.GetCustomAttribute(asm, typeof(AssemblyProductAttribute));\n product = asProduct.Product;\n }\n if (!string.IsNullOrEmpty(company) && !string.IsNullOrEmpty(product))\n {\n string desktopPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),\n product + \".appref-ms\");\n string shortcutPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs),\n Path.Combine(company, product + \".appref-ms\"));\n File.Copy(shortcutPath, desktopPath, true);\n }\n}\ncatch \n{\n // Shortcut could not be created\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9345/"
] |
149,763
|
<p>I'm benchmarking a WPF application on various platforms and I need an easy way to determine if WPF is using hardware or software rendering. </p>
<p>I seem to recall a call to determine this, but can't lay my hands on it right now.</p>
<p>Also, is there an easy, code based way to force one rendering pipeline over the other?</p>
|
[
{
"answer_id": 150005,
"author": "Charley Rathkopf",
"author_id": 10119,
"author_profile": "https://Stackoverflow.com/users/10119",
"pm_score": 3,
"selected": false,
"text": " logger.InfoFormat(\"WPF Tier = {0}\",RenderCapability.Tier / 0x10000);\n RenderCapability.TierChanged +=\n (sender, args) => logger.InfoFormat(\"WPF Tier Changed to {0}\",\n RenderCapability.Tier / 0x10000);\n"
},
{
"answer_id": 157883,
"author": "cplotts",
"author_id": 22294,
"author_profile": "https://Stackoverflow.com/users/22294",
"pm_score": 3,
"selected": false,
"text": "[HKEY_CURRENT_USER\\Software\\Microsoft\\Avalon.Graphics]\n\"DisableHWAcceleration\"=dword:00000001\n [HKEY_CURRENT_USER\\Software\\Microsoft\\Avalon.Graphics]\n\"DisableHWAcceleration\"=dword:00000000\n"
},
{
"answer_id": 2867201,
"author": "user259509",
"author_id": 259509,
"author_profile": "https://Stackoverflow.com/users/259509",
"pm_score": 4,
"selected": false,
"text": "public partial class App : Application \n{ \n protected override void OnStartup(StartupEventArgs e) \n { \n if (WeThinkWeShouldRenderInSoftware()) \n RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly; \n }\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10119/"
] |
149,772
|
<p>Basically the question is how to get from this:</p>
<pre>
foo_id foo_name
1 A
1 B
2 C
</pre>
<p>to this:</p>
<pre>
foo_id foo_name
1 A B
2 C
</pre>
|
[
{
"answer_id": 149799,
"author": "Scott Noyes",
"author_id": 23539,
"author_profile": "https://Stackoverflow.com/users/23539",
"pm_score": 10,
"selected": true,
"text": "SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;\n GROUP_CONCAT"
},
{
"answer_id": 149805,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 7,
"selected": false,
"text": "SELECT id, GROUP_CONCAT( string SEPARATOR ' ') FROM table GROUP BY id\n GROUP_CONCAT"
},
{
"answer_id": 149817,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 4,
"selected": false,
"text": "SELECT id, GROUP_CONCAT(CAST(name as CHAR)) FROM table GROUP BY id\n"
},
{
"answer_id": 3785928,
"author": "Waqar Alamgir",
"author_id": 457124,
"author_profile": "https://Stackoverflow.com/users/457124",
"pm_score": 4,
"selected": false,
"text": "SET group_concat_max_len=100000000;\n SELECT pub_id,GROUP_CONCAT(cate_id SEPARATOR ' ') FROM book_mast GROUP BY pub_id\n"
},
{
"answer_id": 18118387,
"author": "Exundoz",
"author_id": 2663165,
"author_profile": "https://Stackoverflow.com/users/2663165",
"pm_score": 5,
"selected": false,
"text": "SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;\n GROUP_CONCAT([DISTINCT] expr [,expr ...]\n [ORDER BY {unsigned_integer | col_name | expr}\n [ASC | DESC] [,col_name ...]]\n [SEPARATOR str_val])\n mysql> SELECT student_name,\n -> GROUP_CONCAT(DISTINCT test_score\n -> ORDER BY test_score DESC SEPARATOR ' ')\n -> FROM student\n -> GROUP BY student_name;\n"
},
{
"answer_id": 44271351,
"author": "Mauricio Alo",
"author_id": 1902560,
"author_profile": "https://Stackoverflow.com/users/1902560",
"pm_score": 4,
"selected": false,
"text": "SELECT id, GROUP_CONCAT(COALESCE(name,'') SEPARATOR ' ') \nFROM table \nGROUP BY id;\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403/"
] |
149,777
|
<p>i have several common elements (components), that will generate some html. it seems my options are creating a taglib, or just putting that logic into a jsp page and including the jsp.</p>
<p>whats the difference? positives vs negatives?</p>
|
[
{
"answer_id": 149879,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 1,
"selected": false,
"text": "JspFragment"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20641/"
] |
149,784
|
<p><a href="https://stackoverflow.com/questions/57168/how-to-copy-a-row-from-one-sql-server-table-to-another">This question</a> comes close to what I need, but my scenario is slightly different. The source table and destination table are the same and the primary key is a uniqueidentifier (guid). When I try this:</p>
<pre><code>insert into MyTable
select * from MyTable where uniqueId = @Id;
</code></pre>
<p>I obviously get a primary key constraint violation, since I'm attempting to copy over the primary key. Actually, I don't want to copy over the primary key at all. Rather, I want to create a new one. Additionally, I would like to selectively copy over certain fields, and leave the others null. To make matters more complex, I need to take the primary key of the original record, and insert it into another field in the copy (PreviousId field).</p>
<p>I'm sure there is an easy solution to this, I just don't know enough TSQL to know what it is.</p>
|
[
{
"answer_id": 149792,
"author": "AaronSieb",
"author_id": 16911,
"author_profile": "https://Stackoverflow.com/users/16911",
"pm_score": 9,
"selected": true,
"text": "\ninsert into MyTable(field1, field2, id_backup)\n select field1, field2, uniqueId from MyTable where uniqueId = @Id;\n"
},
{
"answer_id": 149793,
"author": "Scott Bevington",
"author_id": 9544,
"author_profile": "https://Stackoverflow.com/users/9544",
"pm_score": 4,
"selected": false,
"text": "INSERT INTO MyTable (FIELD2, FIELD3, ..., FIELD529, PreviousId)\nSELECT FIELD2, NULL, ..., FIELD529, FIELD1\nFROM MyTable\nWHERE FIELD1 = @Id;\n"
},
{
"answer_id": 149804,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 2,
"selected": false,
"text": "insert into MyTable (uniqueId, column1, column2, referencedUniqueId)\nselect NewGuid(), // don't know this syntax, sorry\n column1,\n column2,\n uniqueId,\nfrom MyTable where uniqueId = @Id\n"
},
{
"answer_id": 149822,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 1,
"selected": false,
"text": "insert into MyTable (field1, field2, field3, parentkey)\nselect field1, field2, null, key from MyTable where uniqueId = @Id\n"
},
{
"answer_id": 2461030,
"author": "Denis Kutlubaev",
"author_id": 295517,
"author_profile": "https://Stackoverflow.com/users/295517",
"pm_score": 0,
"selected": false,
"text": "INSERT INTO DENI/FRIEN01P \nSELECT \n RCRDID+112,\n PROFESION,\n NAME,\n SURNAME,\n AGE, \n RCRDTYP, \n RCRDLCU, \n RCRDLCT, \n RCRDLCD \nFROM \n FRIEN01P \n"
},
{
"answer_id": 14427540,
"author": "Rit Man",
"author_id": 1510859,
"author_profile": "https://Stackoverflow.com/users/1510859",
"pm_score": 1,
"selected": false,
"text": "SQLcolums = \"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE (TABLE_NAME = 'TABLE-NAME')\"\n\nSet GetColumns = Conn.Execute(SQLcolums)\nDo WHILE not GetColumns.eof\n\ncolName = GetColumns(\"COLUMN_NAME\")\n IF colName = \"ORIGINAL-IDENTITY-FIELD-NAME\" THEN ' ASSUMING THAT YOUR PRIMARY KEY IS THE FIRST FIELD DONT WORRY ABOUT COMMAS AND SPACES\n columnListSOURCE = colName \n columnListTARGET = \"[PreviousId field name]\"\nELSE\n columnListSOURCE = columnListSOURCE & colName\n columnListTARGET = columnListTARGET & colName\nEND IF\n\nGetColumns.movenext\n\nloop\n\nGetColumns.close \n where SQL = \"INSERT INTO TARGET-TABLE-NAME (\" & columnListTARGET & \") SELECT \" & columnListSOURCE & \" FROM SOURCE-TABLE-NAME WHERE (FIELDNAME = FIELDVALUE)\" \nConn.Execute(SQL)\n"
},
{
"answer_id": 15025236,
"author": "Jonas",
"author_id": 1651165,
"author_profile": "https://Stackoverflow.com/users/1651165",
"pm_score": 7,
"selected": false,
"text": "SELECT * INTO TempTable FROM MyTable_T WHERE id = 1;\nALTER TABLE TempTable DROP COLUMN id;\nINSERT INTO MyTable_T SELECT * FROM TempTable;\nDROP TABLE TempTable;\n CREATE TABLE UPDATE TABLE use MyDatabase; \nSELECT * INTO #TempTable FROM [MyTable] WHERE [IndexField] = :id;\nALTER TABLE #TempTable DROP COLUMN [IndexField]; \nINSERT INTO [MyTable] SELECT * FROM #TempTable; \nDROP TABLE #TempTable;\n"
},
{
"answer_id": 46045294,
"author": "TonyT",
"author_id": 1621506,
"author_profile": "https://Stackoverflow.com/users/1621506",
"pm_score": 3,
"selected": false,
"text": "SELECT * INTO #TempRow FROM SourceTable WHERE KeyColumn = 'ABC';\nUPDATE #TempRow SET KeyColumn = 'XYZ';\nINSERT INTO SourceTable SELECT * FROM #TempRow;\nDELETE #TempRow;\n DROP TABLE #TempRow;\n"
},
{
"answer_id": 50902859,
"author": "Jeyara",
"author_id": 712826,
"author_profile": "https://Stackoverflow.com/users/712826",
"pm_score": 3,
"selected": false,
"text": "\ndeclare @columnsToCopyValues varchar(max), @query varchar(max)\nSET @columnsToCopyValues = ''\n\n--Get all the columns execpt Identity columns and Other columns to be excluded. Say IndentityColumn, Column1, Column2\nSelect @columnsToCopyValues = @columnsToCopyValues + [name] + ', ' from sys.columns c where c.object_id = OBJECT_ID('YourTableName') and name not in ('IndentityColumn','Column1','Column2')\nSelect @columnsToCopyValues = SUBSTRING(@columnsToCopyValues, 0, LEN(@columnsToCopyValues))\nprint @columnsToCopyValues\n\nSelect @query = CONCAT('insert into YourTableName (',@columnsToCopyValues,', Column1, Column2) select ', @columnsToCopyValues, ',''Value1'',''Value2'',', ' from YourTableName where IndentityColumn =''' , @searchVariable,'''')\n\nprint @query\nexec (@query)\n"
},
{
"answer_id": 54237321,
"author": "Daniel Nordh",
"author_id": 9450614,
"author_profile": "https://Stackoverflow.com/users/9450614",
"pm_score": 0,
"selected": false,
"text": "Cn.Execute(\"CREATE TEMPORARY TABLE temprow AS SELECT * FROM product WHERE product_id = '12345'\")\nCn.Execute(\"UPDATE temprow SET product_id = '34567'\")\nCn.Execute(\"INSERT INTO product SELECT * FROM temprow\")\nCn.Execute(\"DELETE temprow\")\nCn.Execute(\"DROP TABLE temprow\")\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
] |
149,796
|
<p>Often I want to add a value to a table or update the value if its key already exists. This can be accomplished in several ways, assuming a primary or unique key is set on the 'user_id' and 'pref_key' columns in the example:</p>
<p><strong>1. Blind insert, update if receiving a duplicate key error:</strong></p>
<pre><code>// Try to insert as a new value
INSERT INTO my_prefs
(user_id, pref_key, pref_value)
VALUES (1234, 'show_help', 'true');
// If a duplicate-key error occurs run an update query
UPDATE my_prefs
SET pref_value = 'true'
WHERE user_id=1234 AND pref_key='show_help';
</code></pre>
<p><strong>2. Check for existence, then select or update:</strong></p>
<pre><code>// Check for existence
SELECT COUNT(*)
FROM my_prefs
WHERE user_id=1234 AND pref_key='show_help';
// If count is zero, insert
INSERT INTO my_prefs
(user_id, pref_key, pref_value)
VALUES (1234, 'show_help', 'true');
// If count is one, update
UPDATE my_prefs
SET pref_value = 'true'
WHERE user_id=1234 AND pref_key='show_help';
</code></pre>
<p>The first way seems to be preferable as it will require only one query for new inserts and two for an update, where as the second way will always require two queries. Is there anything I'm missing though that would make it a bad idea to blindly insert?</p>
|
[
{
"answer_id": 149834,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": "INSERT INTO my_prefs \n(user_id, pref_key, pref_value) \nVALUES (1234, 'show_help', 'true')\nON DUPLICATE KEY \nUPDATE pref_value = 'true'\n"
},
{
"answer_id": 149837,
"author": "Ken",
"author_id": 20074,
"author_profile": "https://Stackoverflow.com/users/20074",
"pm_score": 4,
"selected": false,
"text": "INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]\n[INTO] tbl_name [(col_name,...)]\nSELECT ...\n[ ON DUPLICATE KEY UPDATE col_name=expr, ... ]\n"
},
{
"answer_id": 149841,
"author": "Eric Lamb",
"author_id": 538,
"author_profile": "https://Stackoverflow.com/users/538",
"pm_score": 0,
"selected": false,
"text": "MySQL ON DUPLICATE INSERT INTO my_prefs (user_id, pref_key, pref_value) VALUES (1234, 'show_help', 'true') \nON DUPLICATE KEY UPDATE (pref_key, pref_value) VALUES ('show_help', 'true');\n"
},
{
"answer_id": 149849,
"author": "Georgi",
"author_id": 13209,
"author_profile": "https://Stackoverflow.com/users/13209",
"pm_score": 2,
"selected": false,
"text": "int i = SQL(\"UPDATE my_prefs ...\");\nif(i==0) {\n SQL(\"INSERT INTO my_prefs ...\");\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15872/"
] |
149,821
|
<p>I have the following function that is pulling data from a database. The ajax call is working correctly. How can I send the tab delimited data in my success function to the user? Setting the contect type to "application/vnd.ms-excel" didn't work. The alert on success shows the correctly formatted data.</p>
<pre><code> function SendToExcel() {
$.ajax({
type: "GET",
url: "/Search.aspx",
contentType: "application/vnd.ms-excel",
dataType: "text",
data: "{id: '" + "asdf" + "'}",
success: function(data) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText);
}});
}
</code></pre>
<p>I don't want to display the data in the browser--I want to send it to Excel.</p>
<p><strong>EDIT:</strong> I found a way to do what I wanted. Instead of redirecting the users to a new page that would prompt them to save/open an Excel file, I opened the page inside a hidden iframe. That way, the users click a button, and they are prompted to save/open an Excel file. No page redirection. Is it Ajax? No, but it solves the real problem I had.</p>
<p>Here's the function I'm calling on the button click:</p>
<pre><code> function SendToExcel() {
var dataString = 'type=excel' +
'&Number=' + $('#txtNumber').val() +
'&Reference=' + $('#txtReference').val()
$("#sltCTPick option").each(function (i) {
dataString = dataString + '&Columns=' + this.value;
});
top.iExcelHelper.location.href = "/Reports/JobSearchResults.aspx?" + dataString;;
}
</code></pre>
|
[
{
"answer_id": 4455600,
"author": "fernando",
"author_id": 544005,
"author_profile": "https://Stackoverflow.com/users/544005",
"pm_score": 3,
"selected": false,
"text": "onclick=\"exportExcel(); function exportExcel(){\n var inputs = $(\"#myForm\").serialize();\n var url = '/ajaxresponse.php?select=exportExcel&'+inputs;\n location.href = url;\n}\n case 'exportExcel':{\n ob_end_clean();\n header(\"Content-type: application/vnd.ms-excel\");\n header(\"Content-Disposition: attachment;\n filename=exportFile.xls\");\n echo $html->List($bd->ResultSet($_GET));\n }\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681/"
] |
149,823
|
<p>When I dynamically create a Datagrid and add in a new buttoncolumn how do I access the buttoncolumn_click event? </p>
<p>Thanks.</p>
|
[
{
"answer_id": 150165,
"author": "Collin Estes",
"author_id": 20748,
"author_profile": "https://Stackoverflow.com/users/20748",
"pm_score": 0,
"selected": false,
"text": " Datagridtest.Width = 600;\n Datagridtest.GridLines = GridLines.Both;\n Datagridtest.CellPadding = 1;\n\n ButtonColumn bc = new ButtonColumn();\n bc.CommandName = \"add\";\n bc.HeaderText = \"Event Details\";\n bc.Text = \"Details\";\n bc.ButtonType = System.Web.UI.WebControls.ButtonColumnType.PushButton;\n Datagridtest.Columns.Add(bc);\n PlaceHolder1.Controls.Add(Datagridtest);\n\n Datagridtest.DataSource = dt;\n Datagridtest.DataBind();\n"
},
{
"answer_id": 150288,
"author": "taco",
"author_id": 5203,
"author_profile": "https://Stackoverflow.com/users/5203",
"pm_score": 3,
"selected": true,
"text": "protected void Page_Load(object sender, EventArgs e)\n{\n DataGrid dg = new DataGrid();\n\n dg.GridLines = GridLines.Both;\n\n dg.Columns.Add(new ButtonColumn {\n CommandName = \"add\",\n HeaderText = \"Event Details\",\n Text = \"Details\",\n ButtonType = ButtonColumnType.PushButton\n });\n\n dg.DataSource = getDataTable();\n dg.DataBind();\n\n dg.ItemCommand += new DataGridCommandEventHandler(dg_ItemCommand);\n\n pnlMain.Controls.Add(dg);\n}\n\nprotected void dg_ItemCommand(object source, DataGridCommandEventArgs e)\n{\n if (e.CommandName == \"add\")\n {\n throw new Exception(\"add it!\");\n }\n}\n\nprotected DataTable getDataTable()\n{\n // returns your data table\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20748/"
] |
149,825
|
<p>I ran across the following code in <a href="http://www.quietlyscheming.com/blog/" rel="nofollow noreferrer">Ely Greenfield's</a> SuperImage from his Book component - I understand loader.load() but what does the rest of do?</p>
<pre><code>loader.load((newSource is URLRequest)? newSource:new URLRequest(newSource));
</code></pre>
<p>It looks like some kind of crazy inline if statement but still, I'm a little preplexed. And if it is an if statement - is this way better than a regular if statement?</p>
|
[
{
"answer_id": 149847,
"author": "Matt",
"author_id": 20630,
"author_profile": "https://Stackoverflow.com/users/20630",
"pm_score": 0,
"selected": false,
"text": "String str = null;\nint x = (str != null) ? str.length() : 0;\n String str = null;\nint x;\nif (str != null)\n x = str.length()\nelse\n x = 0;\n"
},
{
"answer_id": 149867,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 5,
"selected": true,
"text": "(expression) ? (evaluate to this if expression is true) : (evaluate to this otherwise);\n if (newSource is URLRequest)\n loader.load(newSource);\nelse\n loader.load(new URLRequest(newSource));\n"
},
{
"answer_id": 687923,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "function myFunction(newSource:Object):SomeClass {\nvar loader:URLLoader = new URLLoader();\nloader.load((newSource is URLRequest)? newSource:new URLRequest(newSource));\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3435/"
] |
149,827
|
<p>I want to be able to run a text editor from my app, as given by the user in the TEXT_EDITOR environment variable. Now, assuming there is nothing in that variable, I want to default to the TextEdit program that ships with OSX. Is it kosher to hardcode /Applications/TextEdit.app/Contents/MacOS/TextEdit into my app, or is there a better way to call the program?</p>
<p>Edit: For the record, I am limited to running a specific application path, in C. I'm not opening a path to a text file.</p>
<p>Edit 2: Seriously people, I'm not opening a file here. I'm asking about an application path for a reason.</p>
|
[
{
"answer_id": 149866,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": -1,
"selected": false,
"text": "open <full path to text file>\n open"
},
{
"answer_id": 149915,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 2,
"selected": false,
"text": ".txt NSWorkspace NSWorkspace"
},
{
"answer_id": 151007,
"author": "Dave Verwer",
"author_id": 4496,
"author_profile": "https://Stackoverflow.com/users/4496",
"pm_score": 3,
"selected": true,
"text": "NSString *path = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@\"com.apple.TextEdit\"];\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3830/"
] |
149,844
|
<p>I'm running my site through the W3C's validator trying to get it to validate as XHTML 1.0 Strict and I've gotten down to a particularly sticky (at least in my experience) validation error. I'm including certain badges from various services in the site that provide their own API and code for inclusion on an external site. These badges use javascript (for the most part) to fill an element that you insert in the markup which requires a child. This means that in the end, perfectly valid markup is generated, but to the validator, all it sees is an incomplete parent-child tag which it then throws an error on.</p>
<p>As a caveat, I understand that I could complain to the services that their badges don't validate. Sans this, I assume that someone has validated their code while including badges like this, and that's what I'm interested in. Answers such as, 'Complain to Flickr about their badge' aren't going to help me much.</p>
<p>An additional caveat: I would prefer that as much as possible the markup remains semantic. I.E. Adding an empty li tag or tr-td pair to make it validate would be an <em>undesirable</em> solution, even though it may be necessary. If that's the only way it can be made to validate, oh well, but please lean answers towards semantic markup.</p>
<p>As an example: </p>
<pre><code><div id="twitter_div">
<h2><a href="http://twitter.com/stopsineman">@Twitter</a></h2>
<ul id="twitter_update_list">
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&amp;count=1"></script>
</ul>
</div>
</code></pre>
<p>Notice the ul tags wrapping the javascript. This eventually gets filled in with lis via the script, but to the validator it only sees the unpopulated ul.</p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 150230,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 4,
"selected": true,
"text": "<div id=\"twitter_div\">\n <h2 class=\"twitter-title\"><a href=\"http://twitter.com/stopsineman\" title=\"Tim's Twitter Page.\">Twitter Updates</a></h2>\n <div id=\"myDiv\" />\n</div> \n\n<script type=\"text/javascript\">\n var placeHolderNode = document.getElementById(\"myDiv\");\n var parentNode = placeHolderNode.parentNode;\n var insertedNode = document.createElement(\"ul\");\n insertedNode .setAttribute(\"id\", \"twitter_update_list\");\n parentNode.insertBefore( insertedNode, placeHolderNode);\n parentNode.remove(placeHolderNode);\n</script>\n<script type=\"text/javascript\" src=\"http://twitter.com/javascripts/blogger.js\"></script>\n<script type=\"text/javascript\" src=\"http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&count=5\"></script>\n"
},
{
"answer_id": 150262,
"author": "Joe Lencioni",
"author_id": 18986,
"author_profile": "https://Stackoverflow.com/users/18986",
"pm_score": 2,
"selected": false,
"text": "<div id=\"twitter_div\">\n <h2><a href=\"http://twitter.com/stopsineman\">@Twitter</a></h2>\n <div id=\"twitter_update_list\"></div>\n</div>\n\n<script type=\"text/javascript\">\nfunction updateTwitterCallback(obj)\n{\n var twitters = obj;\n var statusHTML = \"\";\n var username = \"\";\n for (var i = 0; i < twitters.length; i++)\n {\n username = twitters[i].user.screen_name;\n statusHTML += ('<li><span>' + twitters[i].text + '</span> <a style=\"font-size:85%\" href=\"http://twitter.com/' + username + '/statuses/' + twitters[i].id + '\">' + relative_time(twitters[i].created_at) + '</a></li>');\n }\n document.getElementById('twitter_update_list').innerHTML = '<ul>' + statusHTML + '</ul>';\n}\n</script>\n<script type=\"text/javascript\" src=\"http://twitter.com/javascripts/blogger.js\"></script>\n<script type=\"text/javascript\" src=\"http://twitter.com/statuses/user_timeline/stopsineman.json?callback=updateTwitterCallback&count=1\"></script>\n"
},
{
"answer_id": 3030592,
"author": "Markus",
"author_id": 365455,
"author_profile": "https://Stackoverflow.com/users/365455",
"pm_score": 1,
"selected": false,
"text": "<ul id=\"twitter_update_list\"><li style=\"display:none;\">A</li></ul>\n\n<script type=\"text/javascript\" src=\"http://twitter.com/javascripts/blogger.js\"></script>\n<script type=\"text/javascript\" src=\"http://twitter.com/statuses/user_timeline/01241.json?callback=twitterCallback2&count=1\"></script>\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16562/"
] |
149,848
|
<p>What is a strong way to protect against sql injection for a classic asp app?</p>
<p>FYI I am using it with an access DB. (I didnt write the app)</p>
|
[
{
"answer_id": 149854,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 6,
"selected": true,
"text": "Conn.Execute(\"EXEC usp_ImOnlySafeIfYouCallMeRight '\" + param1 + \"', '\" + param2 + \"'\") ;\n INSERT/UPDATE/DELETE"
},
{
"answer_id": 6995837,
"author": "Plippie",
"author_id": 344117,
"author_profile": "https://Stackoverflow.com/users/344117",
"pm_score": 4,
"selected": false,
"text": "function SQLInject(strWords) \ndim badChars, newChars, i\nbadChars = array(\"select\", \"drop\", \";\", \"--\", \"insert\", \"delete\", \"xp_\") \nnewChars = strWords \nfor i = 0 to uBound(badChars) \nnewChars = replace(newChars, badChars(i), \"\") \nnext \nnewChars = newChars \nnewChars= replace(newChars, \"'\", \"''\")\nnewChars= replace(newChars, \" \", \"\")\nnewChars= replace(newChars, \"'\", \"|\")\nnewChars= replace(newChars, \"|\", \"''\")\nnewChars= replace(newChars, \"\\\"\"\", \"|\")\nnewChars= replace(newChars, \"|\", \"''\")\nSQLInject=newChars\nend function \n\n\nfunction SQLInject2(strWords)\ndim badChars, newChars, tmpChars, regEx, i\nbadChars = array( _\n\"select(.*)(from|with|by){1}\", \"insert(.*)(into|values){1}\", \"update(.*)set\", \"delete(.*)(from|with){1}\", _\n\"drop(.*)(from|aggre|role|assem|key|cert|cont|credential|data|endpoint|event|f ulltext|function|index|login|type|schema|procedure|que|remote|role|route|sign| stat|syno|table|trigger|user|view|xml){1}\", _\n\"alter(.*)(application|assem|key|author|cert|credential|data|endpoint|fulltext |function|index|login|type|schema|procedure|que|remote|role|route|serv|table|u ser|view|xml){1}\", _\n\"xp_\", \"sp_\", \"restore\\s\", \"grant\\s\", \"revoke\\s\", _\n\"dbcc\", \"dump\", \"use\\s\", \"set\\s\", \"truncate\\s\", \"backup\\s\", _\n\"load\\s\", \"save\\s\", \"shutdown\", \"cast(.*)\\(\", \"convert(.*)\\(\", \"execute\\s\", _\n\"updatetext\", \"writetext\", \"reconfigure\", _\n\"/\\*\", \"\\*/\", \";\", \"\\-\\-\", \"\\[\", \"\\]\", \"char(.*)\\(\", \"nchar(.*)\\(\") \nnewChars = strWords\nfor i = 0 to uBound(badChars)\nSet regEx = New RegExp\nregEx.Pattern = badChars(i)\nregEx.IgnoreCase = True\nregEx.Global = True\nnewChars = regEx.Replace(newChars, \"\")\nSet regEx = nothing\nnext\nnewChars = replace(newChars, \"'\", \"''\")\nSqlInject2 = newChars\nend function\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23528/"
] |
149,851
|
<p>I'm consuming a third party .NET WebService in my client application. For debugging purposes I want to capture the SOAP requests that are being sent from my server. How would I go about doing this? This is being done on .NET 2.0 without the use of WCF or WSE.</p>
|
[
{
"answer_id": 4268955,
"author": "Steven de Salas",
"author_id": 448568,
"author_profile": "https://Stackoverflow.com/users/448568",
"pm_score": 4,
"selected": false,
"text": "SoapExtension ProcessMessage public class SoapMessageLogger : SoapExtension\n{\n //…\n public override void ProcessMessage(SoapMessage message)\n {\n switch(message.Stage)\n {\n case SoapMessageStage.BeforeDeserialize:\n LogResponse(message);\n break;\n case SoapMessageStage.AfterSerialize:\n LogResponse(message);\n break;\n // Do nothing on other states\n case SoapMessageStage.AfterDeserialize:\n case SoapMessageStage.BeforeSerialize:\n default:\n break;\n }\n }\n //…\n}\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611/"
] |
149,852
|
<p>I have a couple variants of a program that I want to compare on performance. Both perform essentially the same task.</p>
<p>One does it all in C and memory. The other calls an external utility and does file IO.</p>
<p>How do I reliably compare them? </p>
<p>1) Getting "time on CPU" using "time" favors the second variant for calling system() and doing IO. Even if I add "system" time to "user" time, it'll still not count for time spent blocked on wait().</p>
<p>2) I can't just clock them for they run on a server and can be pushed off the CPU any time. Averaging across 1000s of experiments is a soft option, since I have no idea how my server is utilized - it's a VM on a cluster, it's kind of complicated.</p>
<p>3) profilers do not help since they'll give me time spent in the code, which again favors the version that does system()</p>
<p>I need to add up all CPU time that these programs consume, including user, kernel, IO, and children's recursively. </p>
<p>I expected this to be a common problem, but still don't seem to find a solution.</p>
<p>(Solved with times() - see below. Thanks everybody)</p>
|
[
{
"answer_id": 156887,
"author": "n-alexander",
"author_id": 23420,
"author_profile": "https://Stackoverflow.com/users/23420",
"pm_score": 1,
"selected": false,
"text": " clock_t times(struct tms *buf);\n struct tms {\n clock_t tms_utime; /* user time */\n clock_t tms_stime; /* system time */\n clock_t tms_cutime; /* user time of children */\n clock_t tms_cstime; /* system time of children */\n };\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23420/"
] |
149,860
|
<p>I have a <code>popen()</code> function which executes <code>tail -f sometextfile</code>. Aslong as there is data in the filestream obviously I can get the data through <code>fgets()</code>. Now, if no new data comes from tail, <code>fgets()</code> hangs. I tried <code>ferror()</code> and <code>feof()</code> to no avail. How can I make sure <code>fgets()</code> doesn't try to read data when nothing new is in the file stream? </p>
<p>One of the suggestion was <code>select()</code>. Since this is for Windows Platform select doesn't seem to work as anonymous pipes do not seem to work for it (see <a href="https://stackoverflow.com/questions/152807/what-is-wrong-with-this-popen-select-example" title="this post">this post</a>).</p>
|
[
{
"answer_id": 149885,
"author": "Sufian",
"author_id": 9241,
"author_profile": "https://Stackoverflow.com/users/9241",
"pm_score": 4,
"selected": false,
"text": "fgets() select() poll() epoll() FILE* int fd = fileno(f);"
},
{
"answer_id": 149988,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 5,
"selected": false,
"text": "#include <fcntl.h>\n\nFILE *proc = popen(\"tail -f /tmp/test.txt\", \"r\");\nint fd = fileno(proc);\n\nint flags;\nflags = fcntl(fd, F_GETFL, 0);\nflags |= O_NONBLOCK;\nfcntl(fd, F_SETFL, flags);\n"
},
{
"answer_id": 157981,
"author": "SinisterDex",
"author_id": 10010,
"author_profile": "https://Stackoverflow.com/users/10010",
"pm_score": 1,
"selected": false,
"text": "_beginthread _beginthreadex"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10010/"
] |
149,869
|
<p>Does it make sense to qualify bit fields as signed / unsigned?</p>
|
[
{
"answer_id": 149950,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": false,
"text": "struct {\n /* field 4 bits wide */\n unsigned field1 :4;\n /*\n * unnamed 3 bit field\n * unnamed fields allow for padding\n */\n unsigned :3;\n /*\n * one-bit field\n * can only be 0 or -1 in two's complement!\n */\n signed field2 :1;\n /* align next field on a storage unit */\n unsigned :0;\n unsigned field3 :6;\n}full_of_fields;\n"
},
{
"answer_id": 244355,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "#include <stdio.h>\n\ntypedef struct\n{\n signed s : 1;\n unsigned u : 1;\n} BitStruct;\n\nint main(void)\n{\n BitStruct x;\n\n x.s = 1;\n x.u = 1;\n\n printf(\"s: %d \\t u: %d\\r\\n\", x.s, x.u);\n printf(\"s>0: %d \\t u>0: %d\\r\\n\", x.s > 0, x.u > 0);\n\n return 0;\n}\n s: -1 u: 1\ns>0: 0 u>0: 1\n"
},
{
"answer_id": 4590032,
"author": "Eric",
"author_id": 561994,
"author_profile": "https://Stackoverflow.com/users/561994",
"pm_score": 2,
"selected": false,
"text": "// Fields need to be reordered based on machine/compiler endian orientation\n\ntypedef union _DebugFloat {\n float f;\n unsigned long u;\n struct _Fields {\n signed s : 1;\n unsigned e : 8;\n unsigned m : 23;\n } fields; \n } DebugFloat;\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
149,871
|
<p>I'm building a data warehouse that includes delivery information for restaurants. The data is stored in SQL Server 2005 and is then put into a SQL Server Analysis Services 2005 cube.</p>
<p>The Deliveries information consists of the following tables:</p>
<p><strong>FactDeliveres</strong></p>
<ul>
<li>BranchKey</li>
<li>DeliveryDateKey</li>
<li>ProductKey</li>
<li>InvoiceNumber (DD: degenerate dimension)</li>
<li>Quantity</li>
<li>UnitCosT</li>
<li>Linecost</li>
</ul>
<p><strong>Note:</strong> </p>
<ul>
<li>The granularity of FactDeliveres is each line on the invoice</li>
<li>The Product dimension include supplier information</li>
</ul>
<p><strong>And the problem:</strong> there is no primary key for the fact table. The primary key should be something that uniquely identifies each delivery plus the ProductKey. But I have no way to uniquely identify a delivery.</p>
<p>In the source OLTP database there is a DeliveryID that is unique for every delivery, but that is an internal ID that meaningless to users. The InvoiceNumber is the suppliers' invoices number -- this is typed in manually and so we get duplicates.</p>
<p>In the cube, I created a dimension based only on the InvoiceNumber field in FactDeliveres. That does mean that when you group by InvoiceNumber, you might get 2 deliveries combined only because they (mistakenly) have the same InvoiceNumber.</p>
<p>I feel that I need to include the DeliveryID (to be called DeliveryKey), but I'm not sure how. </p>
<p><strong>So, do I:</strong> </p>
<ol>
<li>Use that as the underlying key for the InvoiceNumber dimension?</li>
<li>Create a DimDelivery that grows every time there is a new delivery? That could mean that some attributes come out of FactDeliveries and go into DimDelivery, like DeliveryDate,Supplier, InvoiceNumber.</li>
</ol>
<p>After all that, I could just ask you: how do I create a Deliveries cube when I have the following information in my source database</p>
<p><strong>DeliveryHeaders</strong></p>
<ul>
<li>DeliveryID (PK)</li>
<li>DeliveryDate</li>
<li>SupplierID (FK)</li>
<li>InvoiceNumber (typed in manually)</li>
</ul>
<p><strong>DeliveryDetails</strong></p>
<ul>
<li>DeliveryID (PK)</li>
<li>ProductID (PK)</li>
<li>Quantity</li>
<li>UnitCosT</li>
</ul>
|
[
{
"answer_id": 149951,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": false,
"text": "Fact table:\nOrderDateID (not in your model, but probably should be, date dimension in a role)\nDeliveryDateID (date dimension in a role)\nSupplierID (supplier dimension surrogate key)\nInvoiceID (invoice dimension surrogate key)\nProductID (product dimension surrogate key)\nQuantity (fact)\nUnitCost (fact)\nInvoiceNumber (optional)\nDeliveryID (optional)\n Supplier Dim:\nSupplierID (surrogate)\nSupplierCode and data\n\nInvoice Dim:\nInvoiceID (surrogate)\nInvoiceNumber (optional)\nDeliveryID (optional)\n\nProduct Dim:\nProductID (surrogate)\nProductCode and Data\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16279/"
] |
149,909
|
<p>I would like to specify a constraint which is another type with a generic argument.</p>
<pre><code>class KeyFrame<T>
{
public float Time;
public T Value;
}
// I want any kind of Keyframe to be accepted
class Timeline<T> where T : Keyframe<*>
{
}
</code></pre>
<p>But this cannot be done in c# as of yet, (and I really doubt it will ever be). Is there any elegant solution to this rather than having to specify the type of the keyframe argument?:</p>
<pre><code>class Timeline<TKeyframe, TKeyframeValue>
where TKeyframe : Keyframe<TKeyframeValue>,
{
}
</code></pre>
|
[
{
"answer_id": 149954,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 2,
"selected": false,
"text": "class TimeLine<T>\n{\nprivate IList<KeyFrame<T>> keyFrameList;\n...\n}\n"
},
{
"answer_id": 149997,
"author": "akmad",
"author_id": 1314,
"author_profile": "https://Stackoverflow.com/users/1314",
"pm_score": 0,
"selected": false,
"text": "Timeline<T> KeyFrame<T> class Timeline<T>\n{\n List<KeyFrame<T>> _frames = new List<KeyFrame<T>>(); //Or whatever...\n\n ...\n}\n Timeline<T> KeyFrame KeyFrame Timeline<T>"
},
{
"answer_id": 150132,
"author": "Troy Howard",
"author_id": 19258,
"author_profile": "https://Stackoverflow.com/users/19258",
"pm_score": 3,
"selected": true,
"text": "public abstract class FooBase\n{\n private FooBase() {} // Not inheritable by anyone else\n public class Foo<U> : FooBase {...generic stuff ...}\n\n ... nongeneric stuff ...\n}\n\npublic class Bar<T> where T: FooBase { ... }\n...\nnew Bar<FooBase.Foo<string>>()\n"
},
{
"answer_id": 3152920,
"author": "Jordão",
"author_id": 31158,
"author_profile": "https://Stackoverflow.com/users/31158",
"pm_score": 0,
"selected": false,
"text": "Timeline KeyFrame class KeyFrame<T> { \n public float Time; \n public T Value; \n\n class Timeline<U> where U : Keyframe<T> { \n } \n} \n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7839/"
] |
149,937
|
<p>Is there a way to deploy a Java program in a format that is not reverse-engineerable? </p>
<p>I know how to convert my application into an executable JAR file, but I want to make sure that the code cannot be reverse engineered, or at least, not easily. </p>
<p>Obfuscation of the source code doesn't count... it makes it harder to understand the code, but does not hide it.</p>
<p>A related question is <em><a href="https://stackoverflow.com/questions/49379/how-to-lock-compiled-java-classes-to-prevent-decompilation">How to lock compiled Java classes to prevent decompilation?</a></em></p>
<hr>
<p>Once I've completed the program, I would still have access to the original source, so maintaining the application would not be the problem. If the application is distributed, I would not want any of the users to be able to decompile it. Obfuscation does not achieve this as the users would still be able to decompile it, and while they would have difficulty following the action flows, they would be able to see the code, and potentially take information out of it.</p>
<p>What I'm concerned about is if there is any information in the code relating to remote access. There is a host to which the application connects using a user-id and password provided by the user. Is there a way to hide the host's address from the user, if that address is located inside the source code?</p>
|
[
{
"answer_id": 149957,
"author": "Tanktalus",
"author_id": 23512,
"author_profile": "https://Stackoverflow.com/users/23512",
"pm_score": 3,
"selected": false,
"text": ".class"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23249/"
] |
149,956
|
<p>Does anyone know of a method to determine when a file copy completes in VBScript? I'm using the following to copy:</p>
<pre><code>set sa = CreateObject("Shell.Application")
set zip = sa.NameSpace(saveFile)
set Fol = sa.NameSpace(folderToZip)
zip.copyHere (Fol.items)
</code></pre>
|
[
{
"answer_id": 149979,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 2,
"selected": false,
"text": "FileSystemObject"
},
{
"answer_id": 149996,
"author": "olle",
"author_id": 22422,
"author_profile": "https://Stackoverflow.com/users/22422",
"pm_score": 4,
"selected": true,
"text": "Do Until zip.Items.Count = Fol.Items.Count\n WScript.Sleep 300\nLoop\n Set FSO = CreateObject( \"Scripting.FileSystemObject\" )\nSet File = FSO.OpenTextFile( saveFile, 2, True )\nFile.Write \"PK\" & Chr(5) & Chr(6) & String( 18, Chr(0) )\nFile.Close\nSet File = Nothing\nSet FSO = Nothing\n"
},
{
"answer_id": 28565054,
"author": "user3013626",
"author_id": 3013626,
"author_profile": "https://Stackoverflow.com/users/3013626",
"pm_score": 0,
"selected": false,
"text": "Const FOF_CREATEPROGRESSDLG = &H0&\nConst ForReading = 1, ForWriting = 2, ForAppending = 8\n\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\n\nstrSource = \" \" ' Source folder path of log files\nstrTarget = \" .zip\" ' backup path where file will be created\n\nAddFilesToZip strSource,strTarget\n\nFunction AddFilesToZip (strSource,strTarget)\nSet r=fso.GetFolder(strSource)\n set file = fso.opentextfile(strTarget,ForWriting,true) \n file.write \"PK\" & chr(5) & chr(6) & string(18,chr(0)) \n file.Close\n Set shl = CreateObject(\"Shell.Application\")\n i = 0\n\n For each f in r.Files\n If fso.GetExtensionName(f) = \"log\" Or fso.GetExtensionName(f) = \"Log\" Or fso.GetExtensionName(f) = \"LOG\" Then\n shl.namespace(strTarget).copyhere(f.Path)', FOF_CREATEPROGRESSDLG \n Do until shl.namespace(strTarget).items.count = i\n wscript.sleep 300\n Loop\n End If\n i = i + 1\n Next\n\n set shl = Nothing\nEnd Function\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14092/"
] |
149,962
|
<p>I have an ASP.NET page which has a button it it. The button click launches a modal dialog box using JavaScript. Based on the value returned by the modal dialog box, I want to proceed with, or cancel the post back that happens. How do I do this?</p>
|
[
{
"answer_id": 149982,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 0,
"selected": false,
"text": "function HandleClick()\n{\n // do some work;\n\nif (some condition) return true; //proceed\nelse return false; //cancel;\n}\n"
},
{
"answer_id": 149986,
"author": "Joe Lencioni",
"author_id": 18986,
"author_profile": "https://Stackoverflow.com/users/18986",
"pm_score": 2,
"selected": false,
"text": "<input type=\"button\" id=\"myButton\" value=\"Click!\" />\n\n<script type=\"text/javascript\">\ndocument.getElementById('myButton').onclick = function() {\n var agree = confirm('Are you sure?');\n if (!agree) return false;\n};\n</script>\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/149962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1909/"
] |
150,010
|
<p>I am creating a "department picker" form that is going to serve as a modal popup form with many of my "primary" forms of a Winforms application. Ideally the user is going to click on an icon next to a text box that will pop up the form, they will select the department they need, and when they click OK, the dialog will close and I will have the value selected for me to update the textbox with.</p>
<p>I've already done the route with passing the owner of the dialog box into the dialog form and having the OK button click event do the proper update, but this forces me to do a DirectCast to the form type and I can then only reuse the picker on the current form.</p>
<p>I have been able to use a ByRef variable in the constructor and successfully update a value, but it works only in the constructor. If I attempt to assign the ByRef value to some internal variable in the Department Picker class, I lose the reference aspect of it. This is my basic code attached to my form:
</p>
<pre><code>Public Class DeptPicker
Private m_TargetResult As String
Public Sub New(ByRef TargetResult As String)
InitializeComponent()
' This works just fine, my "parent" form has the reference value properly updated.
TargetResult = "Booyah!"
' Once I leave the constructor, m_TargetResult is a simple string value that won't update the parent
m_TargetResult = TargetResult
End Sub
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
DialogResult = Windows.Forms.DialogResult.OK
' I get no love here. m_TargetResult is just a string and doesn't push the value back to the referenced variable I want.
m_TargetResult = "That department I selected."
Me.Close()
End Sub
Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
DialogResult = Windows.Forms.DialogResult.Cancel
Me.Close()
End Sub
End Class
</code></pre>
<p>Can somebody tell me what I'm missing here or a different approach to make this happen?</p>
<p><em>Note: Code sample is in VB.NET, but I'll take any C# answers too. 8^D</em></p>
|
[
{
"answer_id": 150021,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 3,
"selected": true,
"text": "using (var dlg = new DeptPicker()) {\n if (dlg.ShowDialog() == DialogResult.OK) {\n myTextBoxOrWhatEver.Text = dlg.TargetResult;\n }\n}\n void okButton_Click(object sender, EventArgs e)\n{\n TargetResult = whatever; // can also do this when the selection changes\n DialogResult = DialogResult.OK;\n Close();\n}\n"
},
{
"answer_id": 150199,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 0,
"selected": false,
"text": "\nPublic Class DeptPicker\n\n Private m_TargetTextBox As TextBox\n\n Public Sub New(ByRef TargetTextBox As TextBox)\n InitializeComponent()\n\n m_TargetTextBox = TargetTextBox\n\n End Sub\n\n Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click\n\n DialogResult = Windows.Forms.DialogResult.OK\n\n ' I get no love here. m_TargetResult is just a string and doesn't push the value back to the referenced variable I want.\n m_TargetTextBox.Text = \"That department I selected.\"\n Me.Close()\n\n End Sub\n\n Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click\n\n DialogResult = Windows.Forms.DialogResult.Cancel\n Me.Close()\n\n End Sub\n\nEnd Class\n"
},
{
"answer_id": 150693,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 0,
"selected": false,
"text": "\nPublic Class DeptPicker\n\n dim dlgResult as DialogResult\n\n Public Function GetSelectedDepartment() As String\n Me.Show vbModal\n If (dlgResult = Windows.Forms.DialogResult.OK) Then\n return \"selected department string here\"\n Else\n return \"sorry, you didnt canceled on the form\"\n End If\n End Function\n\n Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click\n dlgResult = Windows.Forms.DialogResult.OK\n Me.Close()\n End Sub\n\n Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click\n dlgResult = Windows.Forms.DialogResult.Cancel\n Me.Close()\n End Sub\nEnd Class\n"
},
{
"answer_id": 154398,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " // This code in your dialog form. Hide the base showdialog method \n // and implement your own versions\n public new string ShowDialog() {\n return this.ShowDialog(null);\n }\n\n public new string ShowDialog(IWin32Window owner) {\n // Call the base implementation of show dialog\n base.ShowDialog(owner);\n\n // You get here after the close button is clicked and the form is hidden. Capture the data you want.\n string s = this.someControl.Text;\n\n // Now really close the form and return the value\n this.Close();\n return s;\n }\n\n // On close, just hide. Close in the show dialog method\n private void closeButton_Click(object sender, EventArgs e) {\n this.Hide();\n }\n\n // This code in your calling form\n MyCustomForm f = new MyCustomForm();\n string myAnswer = f.ShowDialog();\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/150010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71/"
] |
150,011
|
<p>My clients application exports and imports quite a few variables of type real through a text file using writeln and readln. I've tried to increase the width of the fields written so the code looks like: </p>
<pre><code>writeln(file, exportRealvalue:30); //using excess width of field
....
readln(file, importRealvalue);
</code></pre>
<p>When I export and then import and export again and compare the files I get a difference in the last two digits, e.g (might be off on the actual number of digits here but you get it): </p>
<pre><code>-1.23456789012E-0002
-1.23456789034E-0002
</code></pre>
<p>This actually makes a difference in the app so the client wants to know what I can do about it. Now I'm not sure it's only the write/read that does it but I thought I'd throw a quick question out there before I dive into the hey stack again. Do I need to go binary on this?</p>
<p>This is not an app dealing with currency or something, I just write and read the values to/from file. I know floating points are a bit strange sometimes and I thought one of the routines (writeln/readln) may have some funny business going on.</p>
|
[
{
"answer_id": 150644,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 3,
"selected": true,
"text": "WriteLn(RealVar:12:3);\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/150011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9077/"
] |
150,017
|
<p>I have a query that I'm executing from a .NET application to a SQL Server database and it seems to take quite a while to complete (5+ Minutes). I created a test app in c# to try to see what was talking so long (the query should return quickly). </p>
<p>As I was reconstructing the query by adding in elements to see which portion was taking so long, I ended up reconstructing the query practically verbatim where the only difference was the spaces in the original query and a capitalization difference. This difference returned a result in about 100 milliseconds.</p>
<p>Has anybody seen this before? I'm wondering if there are services turned off in our server (since a coworker has the same problem) or on our computers.</p>
<p>Thanks in advance for any help with this.</p>
<p>Code Sample Below (The Difference in in the first line of the query at the end (fk_source vs. fk _Source):</p>
<pre><code>//Original
OleDbCommand comm = new OleDbCommand("select min(ctc.serial_no) as MIN_INTERVAL from countstypecode ctc, source s, countstype ct, counts c where ct.value_id=c.value_id and s.c_id=ct.fk_source and " +
"ct.timeinterval=ctc.typename and ct.timeinterval in ('15min','1h','1day') and c.time_stamp >= CONVERT(datetime,'01-01-2008',105) and c.time_stamp < " +
"CONVERT(datetime,'01-01-2009',105) and s.c_id = '27038dbb19ed93db011a315297df3b7a'", dbConn);
//Rebuilt
OleDbCommand comm = new OleDbCommand("select min(ctc.serial_no) as MIN_INTERVAL from countstypecode ctc, source s, countstype ct, counts c where ct.value_id=c.value_id and s.c_id=ct.fk_Source and " +
"ct.timeinterval=ctc.typename and ct.timeinterval in ('15min','1h','1day') and c.time_stamp >= CONVERT(datetime,'01-01-2008',105) and c.time_stamp < " +
"CONVERT(datetime,'01-01-2009',105) and s.c_id='27038dbb19ed93db011a315297df3b7a'", dbConn);
</code></pre>
|
[
{
"answer_id": 150408,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 3,
"selected": true,
"text": "DBCC MemoryStatus\n\nSelect Columns... From TABLES.... Where....\n\ndbcc MemoryStatus\n\nSelect Columns... From tables.... Where....\n\ndbcc MemoryStatus\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/150017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23553/"
] |
150,031
|
<p>Does anyone have a good technique (or tutorial) to implement rulers within a C# Windows Forms application? I want to display an image while showing rulers that indicate your mouse position to allow a more accurate positioning of the cursor. Just like the image below:</p>
<p><img src="https://i.stack.imgur.com/QfIIi.png" alt="Ruler depicting where the cursor is located."></p>
<p>I tried using splitter controls to hold the tick marks but I don't know how to make the top-left the gray blank area. Any advice? Thanks.</p>
|
[
{
"answer_id": 150065,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": true,
"text": "Paint()"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/150031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13115/"
] |
150,033
|
<p>What is the easiest way to match non-ASCII characters in a regex? I would like to match all words individually in an input string, but the language may not be English, so I will need to match things like ü, ö, ß, and ñ. Also, this is in Javascript/jQuery, so any solution will need to apply to that. </p>
|
[
{
"answer_id": 150078,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 9,
"selected": true,
"text": "[^\\x00-\\x7F]+\n [^\\u0000-\\u007F]+\n"
},
{
"answer_id": 873600,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "\\p{charclass} [allthecharactersintheclass]"
},
{
"answer_id": 22075070,
"author": "rjanjic",
"author_id": 1934618,
"author_profile": "https://Stackoverflow.com/users/1934618",
"pm_score": 8,
"selected": false,
"text": "var words_in_text = function (text) {\n var regex = /([\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0\\u08A2-\\u08AC\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6E5\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA80-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]+)/g;\n return text.match(regex);\n};\n\nwords_in_text('Düsseldorf, Köln, Москва, 北京市, إسرائيل !@#$');\n\n// returns array [\"Düsseldorf\", \"Köln\", \"Москва\", \"北京市\", \"إسرائيل\"]\n"
},
{
"answer_id": 35743562,
"author": "Arkadiusz Kałkus",
"author_id": 3775079,
"author_profile": "https://Stackoverflow.com/users/3775079",
"pm_score": 5,
"selected": false,
"text": "können móc ([^\\x00-\\x7F]|\\w)+\n ([^\\u0000-\\u007F]|\\w)+\n [^\\x00-\\x7F] [^\\u0000-\\u007F] (|) \\w ([^\\u0000-\\u007F]|\\w) +"
},
{
"answer_id": 48902765,
"author": "Loilo",
"author_id": 2048874,
"author_profile": "https://Stackoverflow.com/users/2048874",
"pm_score": 7,
"selected": false,
"text": "/\\p{Letter}/u\n /\\p{L}/u\n /[\\p{L}-]/u\n /[\\p{L}-]+/ug\n 'Düsseldorf, Köln, Москва, 北京市, إسرائيل !@#$'.match(/[\\p{L}-]+/ug)\n\n// [\"Düsseldorf\", \"Köln\", \"Москва\", \"北京市\", \"إسرائيل\"]\n /(?:[A-Za-z\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u09FC\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0AF9\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58-\\u0C5A\\u0C60\\u0C61\\u0C80\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D54-\\u0D56\\u0D5F-\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16F1-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u1884\\u1887-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C88\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6E5\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB65\\uAB70-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]|\\uD800[\\uDC00-\\uDC0B\\uDC0D-\\uDC26\\uDC28-\\uDC3A\\uDC3C\\uDC3D\\uDC3F-\\uDC4D\\uDC50-\\uDC5D\\uDC80-\\uDCFA\\uDE80-\\uDE9C\\uDEA0-\\uDED0\\uDF00-\\uDF1F\\uDF2D-\\uDF40\\uDF42-\\uDF49\\uDF50-\\uDF75\\uDF80-\\uDF9D\\uDFA0-\\uDFC3\\uDFC8-\\uDFCF]|\\uD801[\\uDC00-\\uDC9D\\uDCB0-\\uDCD3\\uDCD8-\\uDCFB\\uDD00-\\uDD27\\uDD30-\\uDD63\\uDE00-\\uDF36\\uDF40-\\uDF55\\uDF60-\\uDF67]|\\uD802[\\uDC00-\\uDC05\\uDC08\\uDC0A-\\uDC35\\uDC37\\uDC38\\uDC3C\\uDC3F-\\uDC55\\uDC60-\\uDC76\\uDC80-\\uDC9E\\uDCE0-\\uDCF2\\uDCF4\\uDCF5\\uDD00-\\uDD15\\uDD20-\\uDD39\\uDD80-\\uDDB7\\uDDBE\\uDDBF\\uDE00\\uDE10-\\uDE13\\uDE15-\\uDE17\\uDE19-\\uDE33\\uDE60-\\uDE7C\\uDE80-\\uDE9C\\uDEC0-\\uDEC7\\uDEC9-\\uDEE4\\uDF00-\\uDF35\\uDF40-\\uDF55\\uDF60-\\uDF72\\uDF80-\\uDF91]|\\uD803[\\uDC00-\\uDC48\\uDC80-\\uDCB2\\uDCC0-\\uDCF2]|\\uD804[\\uDC03-\\uDC37\\uDC83-\\uDCAF\\uDCD0-\\uDCE8\\uDD03-\\uDD26\\uDD50-\\uDD72\\uDD76\\uDD83-\\uDDB2\\uDDC1-\\uDDC4\\uDDDA\\uDDDC\\uDE00-\\uDE11\\uDE13-\\uDE2B\\uDE80-\\uDE86\\uDE88\\uDE8A-\\uDE8D\\uDE8F-\\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEDE\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3D\\uDF50\\uDF5D-\\uDF61]|\\uD805[\\uDC00-\\uDC34\\uDC47-\\uDC4A\\uDC80-\\uDCAF\\uDCC4\\uDCC5\\uDCC7\\uDD80-\\uDDAE\\uDDD8-\\uDDDB\\uDE00-\\uDE2F\\uDE44\\uDE80-\\uDEAA\\uDF00-\\uDF19]|\\uD806[\\uDCA0-\\uDCDF\\uDCFF\\uDE00\\uDE0B-\\uDE32\\uDE3A\\uDE50\\uDE5C-\\uDE83\\uDE86-\\uDE89\\uDEC0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC2E\\uDC40\\uDC72-\\uDC8F\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD30\\uDD46]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC80-\\uDD43]|[\\uD80C\\uD81C-\\uD820\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDED0-\\uDEED\\uDF00-\\uDF2F\\uDF40-\\uDF43\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDF00-\\uDF44\\uDF50\\uDF93-\\uDF9F\\uDFE0\\uDFE1]|\\uD821[\\uDC00-\\uDFEC]|\\uD822[\\uDC00-\\uDEF2]|\\uD82C[\\uDC00-\\uDD1E\\uDD70-\\uDEFB]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDEA5\\uDEA8-\\uDEC0\\uDEC2-\\uDEDA\\uDEDC-\\uDEFA\\uDEFC-\\uDF14\\uDF16-\\uDF34\\uDF36-\\uDF4E\\uDF50-\\uDF6E\\uDF70-\\uDF88\\uDF8A-\\uDFA8\\uDFAA-\\uDFC2\\uDFC4-\\uDFCB]|\\uD83A[\\uDC00-\\uDCC4\\uDD00-\\uDD43]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D])/\n"
},
{
"answer_id": 62125247,
"author": "Jonathan",
"author_id": 271450,
"author_profile": "https://Stackoverflow.com/users/271450",
"pm_score": 0,
"selected": false,
"text": "([^\\t]+)\\t\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/150033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] |
150,038
|
<p>I have a middle tier containing several related objects and a data tier that is using a DataSet with several DataTables and relationships.</p>
<p>I want to call a Save method on one of my objects (a parent object) and have its private variable data transformed into a DataRow and added to a DataTable. Some of the private variable data are actually other objects (child object) that each need to have their own Save method called and their own variable data persisted.</p>
<p>How do I "lace" this together? What parts of a DataSet should be instantiated in the ParentObject and what needs to be passed to the ChildObjects so they can add themselves to the dataset?</p>
<p>Also, how do I wire the relationships together for 2 tables?</p>
<p>The examples I have seen for an Order OrderDetail relationship create the OrderRow and the OrderDetailRow then call OrderDetailRow.SetParentRow(OrderDetail)</p>
<p>I do not think this will work for me since my Order and OrderDetail (using their examples naming) are in separate classes and the examples have it all happening in a Big Honking Method.</p>
<p>Thank you,
Keith</p>
|
[
{
"answer_id": 151255,
"author": "Keith Sirmons",
"author_id": 1048,
"author_profile": "https://Stackoverflow.com/users/1048",
"pm_score": 0,
"selected": false,
"text": "// some random save event in a gui.cs//\npublic void HandleSaveButtonClick()\n{ parentObject.Save(); }\n\n\n// Save inside the parentObject.cs //\npublic void Save()\n{ \n CustomDataSet dataSet = new CustomDataSet();\n\n ParentObjectTableAdapter parentTableAdapter = new ParentObjectTableAdapter();\n\n DataTable dt = dataSet.ParentTable;\n DataRow newParentDataRow = dt.NewRow();\n newParentDataRow[\"Property1\"] = \"Hello\";\n newParentDataRow[\"Property2\"] = \"World\";\n dt.Rows.Add(newParentDataRow);\n\n parentTableAdapter.Update(dataSet.ParentTable);\n\n //save children\n _child1.Save(dataSet, newParentDataRow)\n\n\n dataSet.AcceptChanges();\n}\n\n//Save inside child1.cs //\npublic void Save(CustomDataSet dataSet, DataRow parentRow)\n{\n\n Child1TableAdapter childTableAdapter= new Child1TableAdapter();\n\n DataTable dt = dataSet.ChildTable;\n\n DataRow dr = dt.NewRow();\n dr.SetParentRow(parentRow);\n dr[\"CProp1\"] = \"Child Property 1\"; \n dt.Rows.Add(dr);\n\n childTableAdapter.Update(dataSet.ChildTable);\n\n}\n"
},
{
"answer_id": 237114,
"author": "Thomas Eyde",
"author_id": 3282,
"author_profile": "https://Stackoverflow.com/users/3282",
"pm_score": 2,
"selected": false,
"text": "var order = repository.GetOrder(id);\nrepository.Save(order);\n var ds = db.GetOrderAndDetailsBy(id);\nvar order = new Order();\nUpdateOrder(ds, order);\nUpdateOrderDetails(ds, order); // creates and updates OrderDetail, add it to order.\nmap.Register(ds, order);\n var ds = map.GetDataSetFor(order);\nUpdateFromOrder(ds, order);\nforeach(var detail in order.Details) UpdateFromDetail(ds.OrderDetail, detail);\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/150038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048/"
] |
150,042
|
<p>I have tried this...</p>
<pre><code>Dim myMatches As String() =
System.Text.RegularExpressions.Regex.Split(postRow.Item("Post"), "\b\#\b")
</code></pre>
<p>But it is splitting all words, I want an array of words that start with#</p>
<p>Thanks!</p>
|
[
{
"answer_id": 150086,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 1,
"selected": false,
"text": "\"\\b#\\w+\\b\"\n"
},
{
"answer_id": 150087,
"author": "Rory Becker",
"author_id": 11356,
"author_profile": "https://Stackoverflow.com/users/11356",
"pm_score": 3,
"selected": true,
"text": "Regex MyRegex = new Regex(\"\\\\#\\\\w+\");\nMatchCollection ms = MyRegex.Matches(InputText);\n Dim MyRegex as Regex = new Regex(\"\\#\\w+\")\nDim ms as MatchCollection = MyRegex.Matches(InputText)\n"
},
{
"answer_id": 150088,
"author": "Joe Lencioni",
"author_id": 18986,
"author_profile": "https://Stackoverflow.com/users/18986",
"pm_score": 1,
"selected": false,
"text": "preg_match_all() $text = 'Test #string testing #my test #text.';\npreg_match_all('/#[\\S]+/', $text, $matches);\n\necho '<pre>';\nprint_r($matches[0]);\necho '</pre>';\n"
},
{
"answer_id": 150100,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "text = \"what #regEx can I use to #split a #string into whole words but only\" \n// what #regEx can I use to #split a #string into whole words but only\"\ntext.match(/#\\w+/g);\n// [#regEx,#split,#string]\n"
},
{
"answer_id": 150107,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 0,
"selected": false,
"text": "\\#:w"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/150042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6514/"
] |
150,044
|
<p>I'm new to ASP.NET and want to have an asp:content control for the page title, but I want that value to be used for the tag and for a page header. When I tried to do this with two tags with the same id, it complained that I couldn't have two tags with the same id. Is there a way to achieve this with contentplaceholders, and if not what would be the easiest way to use a single parameter to the masterpage twice in one page?</p>
|
[
{
"answer_id": 150072,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": true,
"text": "<%@ Page Language=\"C#\" MasterPageFile=\"~/default.master\" Title=\"My Content Title\" %>\n <h1><%= this.Page.Title %></h3>\n"
},
{
"answer_id": 150172,
"author": "Ronald Wildenberg",
"author_id": 23562,
"author_profile": "https://Stackoverflow.com/users/23562",
"pm_score": 0,
"selected": false,
"text": "asp:Label pageTitle sameTitle public void SetPageTitle(string title)\n{\n pageTitle.Text = title;\n sameTitle.Text = title;\n}\n Master SetPageTitle PageLoad ((MyMasterPage) Master).SetPageTitle(\"My content page\");\n MasterType Master Master.SetPageTitle(\"My content page\");\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/150044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6222/"
] |
150,047
|
<p>Does anyone know how to get the name of the TARGET (/t) called from the MSBuild command line? There are a few types of targets that can be called and I want to use that property in a notification to users.</p>
<p>Example:</p>
<pre><code>msbuild Project.proj /t:ApplicationDeployment /p:Environment=DEV
</code></pre>
<p>I want access to the target words <code>ApplicationDeployment</code> in my .Proj file. </p>
<p>Is there a property I can access? Any clue how to do this?</p>
<p><strong>EDIT:</strong> I do not want to have to also pass in a property to get this.</p>
<p><strong>UPDATE:</strong> This is based on <strong>deployment scripts</strong> using MSBuild scripts. My build server is not used for deploying code, only for building. The build server itself has build notifications that can be opted into.</p>
|
[
{
"answer_id": 150271,
"author": "Tim Booker",
"author_id": 10046,
"author_profile": "https://Stackoverflow.com/users/10046",
"pm_score": 4,
"selected": false,
"text": "msbuild Project.proj /t:ApplicationDeployment /p:Environment=DEV;MyValue=ApplicationDeployment\n <Target Name=\"ApplicationDeployment\">\n<PropertyGroup>\n <InvokedTarget Condition=\"'${InvokedTarget}'==''\">ApplicationDeployment</InvokedTarget>\n</PropertyGroup>\n\n...\n</Target>\n"
},
{
"answer_id": 153741,
"author": "ferventcoder",
"author_id": 18475,
"author_profile": "https://Stackoverflow.com/users/18475",
"pm_score": 4,
"selected": true,
"text": "<Target Name=\"ApplicationDeployment\" >\n <CreateProperty Value=\"$(MSBuildProjectName) - $(Environment) - Application Deployment Complete\">\n <Output TaskParameter=\"Value\" PropertyName=\"DeploymentCompleteNotifySubject\" />\n </CreateProperty>\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/150047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18475/"
] |
150,053
|
<p>How can I limit my post-build events to running only for one type of build?</p>
<p>I'm using the events to copy DLL files to a local IIS virtual directory, but I don't want this happening on the build server in release mode.</p>
|
[
{
"answer_id": 150070,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 3,
"selected": false,
"text": "$(ConfigurationName)"
},
{
"answer_id": 150089,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 7,
"selected": false,
"text": "<PropertyGroup Condition=\" '$(Configuration)' == 'Debug' \">\n <PostBuildEvent>start gpedit</PostBuildEvent>\n</PropertyGroup>\n"
},
{
"answer_id": 150092,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 11,
"selected": true,
"text": "$(ConfigurationName) if $(ConfigurationName) == Debug xcopy something somewhere\n"
},
{
"answer_id": 1176725,
"author": "CestLaGalere",
"author_id": 6684,
"author_profile": "https://Stackoverflow.com/users/6684",
"pm_score": 7,
"selected": false,
"text": "if $(ConfigurationName) == Debug goto :debug\n\n:release\nsigntool.exe ....\nxcopy ...\n\ngoto :exit\n\n:debug\n' Debug items in here\n\n:exit\n %1 $(OutputPath)"
},
{
"answer_id": 3547790,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 9,
"selected": false,
"text": "if $(ConfigurationName) == Debug (\n copy \"$(TargetDir)myapp.dll\" \"c:\\delivery\\bin\" /y\n copy \"$(TargetDir)myapp.dll.config\" \"c:\\delivery\\bin\" /y\n) ELSE (\n echo \"why, Microsoft, why\".\n)\n"
},
{
"answer_id": 13874593,
"author": "mawl",
"author_id": 260865,
"author_profile": "https://Stackoverflow.com/users/260865",
"pm_score": -1,
"selected": false,
"text": "if $(Configuration) == Debug xcopy\n $(ConfigurationName)"
},
{
"answer_id": 35554802,
"author": "Eric Bole-Feysot",
"author_id": 616274,
"author_profile": "https://Stackoverflow.com/users/616274",
"pm_score": 4,
"selected": false,
"text": "if \"$(ConfigurationName)\"==\"My Debug CFG\" ( xcopy \"$(TargetDir)test1.tmp\" \"$(TargetDir)test.xml\" /y) else ( xcopy \"$(TargetDir)test2.tmp\" \"$(TargetDir)test.xml\" /y)\n"
},
{
"answer_id": 44828684,
"author": "Jaan Marks",
"author_id": 6415166,
"author_profile": "https://Stackoverflow.com/users/6415166",
"pm_score": -1,
"selected": false,
"text": "if $(ConfigurationName) == Debug (\nxcopy /Y \"$(ProjectDir)..\\..\\lib\\*.dll\" \"$(TargetDir)\"\n) ELSE (echo \"Not Debug mode, no file copy from lib\")\n"
},
{
"answer_id": 59650562,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 5,
"selected": false,
"text": ".csproj Target <Target Name=\"PostBuild\" AfterTargets=\"PostBuildEvent\" Condition=\"'$(Configuration)' == 'Debug'\">\n <Exec Command=\"nswag run nswag.json\" />\n</Target>\n Configuration"
},
{
"answer_id": 70988151,
"author": "plcnut",
"author_id": 4770398,
"author_profile": "https://Stackoverflow.com/users/4770398",
"pm_score": 1,
"selected": false,
"text": " <Target Name=\"PostBuild\" AfterTargets=\"PostBuildEvent\" Condition=\" '$(Configuration)' != 'Debug' AND '$(Configuration)' != 'Release' \">\n <Exec Command=\"powershell.exe -ExecutionPolicy Unrestricted -NoProfile -NonInteractive -File $(ProjectDir)postBuild.ps1 -ProjectPath $(ProjectPath) -Build $(Configuration)\" />\n </Target>\n"
},
{
"answer_id": 73445133,
"author": "IAbstract",
"author_id": 210709,
"author_profile": "https://Stackoverflow.com/users/210709",
"pm_score": 2,
"selected": false,
"text": "Configuration <Target Name=\"PostBuild\" AfterTargets=\"PostBuildEvent\">\n <Exec Command=\"if $(Configuration) == Debug (dotnet pack --no-build -o ~/../../../../../nuget-repo/debug -p:PackageVersion=$(VersionInfo)) else (dotnet pack --no-build -o ~/../../../../../nuget-repo -p:PackageVersion=$(VersionInfo))\" />\n</Target>\n <Target Name=\"PostBuild\" AfterTargets=\"PostBuildEvent\">\n <Exec Condition=\"'$(Configuration)' == 'Debug'\" Command=\"dotnet pack --no-build -o ~/../../../../../nuget-repo/debug -p:PackageVersion=$(VersionInfo)\" />\n <Exec Condition=\"'$(Configuration)' == 'Release'\" Command=\"dotnet pack --no-build -o ~/../../../../../nuget-repo -p:PackageVersion=$(VersionInfo)\" />\n</Target>\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/150053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3615/"
] |
150,058
|
<p>mysql5.0 with a pair of databases "A" and "B", both with large innodb tables. "drop database A;" freezes database "B" for a couple minutes. Nothing is using "A" at that point, so why is this such an intensive operation?</p>
<p>Bonus points: Given that we use "A", upload data into "B", and then switch to using "B", how can we do this faster? Dropping databases isn't the sort of thing one typically has to do all the time, so this is a bit off the charts.</p>
|
[
{
"answer_id": 150763,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 3,
"selected": false,
"text": "innodb_file_per_table = 1\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/150058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12332/"
] |
150,076
|
<p>I created a Rails application normally. Then created the scaffold for an event class. Then tried the following code. When run it complains about a InvalidAuthenticityToken when the destroy method is executed. How do I authenticate to avoid this response?</p>
<pre><code>require 'rubygems'
require 'activeresource'
class Event < ActiveResource::Base
self.site = "http://localhost:3000"
end
e = Event.create(
:name => "Shortest Event Ever!",
:starts_at => 1.second.ago,
:capacity => 25,
:price => 10.00)
e.destroy
</code></pre>
|
[
{
"answer_id": 150763,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 3,
"selected": false,
"text": "innodb_file_per_table = 1\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/150076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/219658/"
] |
150,084
|
<p>I have a collection of data stored in XDocuments and DataTables, and I'd like to address both as a single unified data space with XPath queries. So, for example, "/Root/Tables/Orders/FirstName" would fetch the value of the Firstname column in every row of the DataTable named "Orders". </p>
<p>Is there a way to do this without copying all of the records in the DataTable into the XDocument?</p>
<p>I'm using .Net 3.5</p>
|
[
{
"answer_id": 226818,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 2,
"selected": true,
"text": "Dictionary<string,DataTable> Tables = new Dictionary<string,DataTable>();\n// ... populate dictionary of tables ...\nXElement TableRoot = new XStreamingElement(\"Tables\",\n from t in Tables\n select new XStreamingElement(t.Key,\n from DataRow r in t.Value.Rows\n select new XStreamingElement(\"row\",\n from DataColumn c in t.Value.Columns\n select new XElement(c.ColumnName, r[c])))))\n <Tables>\n <Orders>\n <row>\n <sku>12345</sku>\n <quantity>2</quantity>\n <price>5.95</price>\n </row>\n <row>\n <sku>54321</sku>\n <quantity>3</quantity>\n <price>2.95</price>\n </row>\n </Orders>\n</Tables>\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/150084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5548/"
] |
150,095
|
<p>I need to substitute the value of a string into my regular expression in Ruby. Is there an easy way to do this? For example:</p>
<pre><code>foo = "0.0.0.0"
goo = "here is some other stuff 0.0.0.0"
if goo =~ /value of foo here dynamically/
puts "success!"
end
</code></pre>
|
[
{
"answer_id": 150108,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "if goo =~ Regexp.new(foo) # Evaluates to /0.0.0.0/\n"
},
{
"answer_id": 150110,
"author": "JasonTrue",
"author_id": 13433,
"author_profile": "https://Stackoverflow.com/users/13433",
"pm_score": 3,
"selected": false,
"text": "Regexp.escape(foo) \"my stuff #{mysubstitutionvariable}\" !goo.match(foo).nil?"
},
{
"answer_id": 150111,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 3,
"selected": false,
"text": "Regexp.compile(Regexp.escape(foo))\n"
},
{
"answer_id": 150115,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 9,
"selected": true,
"text": "if goo =~ /#{Regexp.quote(foo)}/\n#...\n"
},
{
"answer_id": 150116,
"author": "Mike Breen",
"author_id": 22346,
"author_profile": "https://Stackoverflow.com/users/22346",
"pm_score": -1,
"selected": false,
"text": "foo = \"0.0.0.0\"\ngoo = \"here is some other stuff 0.0.0.0\" \n\nputs \"success!\" if goo =~ /#{foo}/\n"
},
{
"answer_id": 150598,
"author": "glenn mcdonald",
"author_id": 7919,
"author_profile": "https://Stackoverflow.com/users/7919",
"pm_score": 7,
"selected": false,
"text": "Regexp.quote if goo =~ /#{Regexp.quote(foo)}/\n if goo =~ /#{foo}/\n \"0.0.0.0\" \"0a0b0c0\" if goo.include?(foo)\n"
},
{
"answer_id": 19717549,
"author": "Plasmarob",
"author_id": 2225842,
"author_profile": "https://Stackoverflow.com/users/2225842",
"pm_score": 2,
"selected": false,
"text": "IP_REGEX = '\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'\n\nmy_str = \"192.0.89.234 blahblah text 1.2, 1.4\" # get the first ssh key \n# replace the ip, for demonstration\nmy_str.gsub!(/#{IP_REGEX}/,\"192.0.2.0\") \nputs my_str # \"192.0.2.0 blahblah text 1.2, 1.4\"\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/150095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] |
150,113
|
<p>An older application using System.Web.Mail is throwing an exception on emails coming from <em>hr@domain.com</em>. Other addresses appear to be working correctly. We changed our mail server to Exchange 2007 when the errors started, so I assume that is where the problem is. Does anyone know what is happening?</p>
<p>Here is the exception and stack trace:</p>
<blockquote>
<p>System.Web.HttpException: Could not access 'CDO.Message' object. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x80040212): The transport lost its connection to the server.<br/>
<br/>
--- End of inner exception stack trace ---<br/>
at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)<br/>
at System.RuntimeType.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters)<br/>
at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args)<br/>
--- End of inner exception stack trace ---<br/>
at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args)<br/>
at System.Web.Mail.CdoSysHelper.Send(MailMessage message)<br/>
at System.Web.Mail.SmtpMail.Send(MailMessage message)<br/>
at ProcessEmail.Main()<br/></p>
</blockquote>
|
[
{
"answer_id": 150108,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "if goo =~ Regexp.new(foo) # Evaluates to /0.0.0.0/\n"
},
{
"answer_id": 150110,
"author": "JasonTrue",
"author_id": 13433,
"author_profile": "https://Stackoverflow.com/users/13433",
"pm_score": 3,
"selected": false,
"text": "Regexp.escape(foo) \"my stuff #{mysubstitutionvariable}\" !goo.match(foo).nil?"
},
{
"answer_id": 150111,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 3,
"selected": false,
"text": "Regexp.compile(Regexp.escape(foo))\n"
},
{
"answer_id": 150115,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 9,
"selected": true,
"text": "if goo =~ /#{Regexp.quote(foo)}/\n#...\n"
},
{
"answer_id": 150116,
"author": "Mike Breen",
"author_id": 22346,
"author_profile": "https://Stackoverflow.com/users/22346",
"pm_score": -1,
"selected": false,
"text": "foo = \"0.0.0.0\"\ngoo = \"here is some other stuff 0.0.0.0\" \n\nputs \"success!\" if goo =~ /#{foo}/\n"
},
{
"answer_id": 150598,
"author": "glenn mcdonald",
"author_id": 7919,
"author_profile": "https://Stackoverflow.com/users/7919",
"pm_score": 7,
"selected": false,
"text": "Regexp.quote if goo =~ /#{Regexp.quote(foo)}/\n if goo =~ /#{foo}/\n \"0.0.0.0\" \"0a0b0c0\" if goo.include?(foo)\n"
},
{
"answer_id": 19717549,
"author": "Plasmarob",
"author_id": 2225842,
"author_profile": "https://Stackoverflow.com/users/2225842",
"pm_score": 2,
"selected": false,
"text": "IP_REGEX = '\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'\n\nmy_str = \"192.0.89.234 blahblah text 1.2, 1.4\" # get the first ssh key \n# replace the ip, for demonstration\nmy_str.gsub!(/#{IP_REGEX}/,\"192.0.2.0\") \nputs my_str # \"192.0.2.0 blahblah text 1.2, 1.4\"\n"
}
] |
2008/09/29
|
[
"https://Stackoverflow.com/questions/150113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17287/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.