pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
14,390,056
0
<p>one possibility:</p> <p>open your mysql/bin/my.ini, change </p> <p><code>max_allowed_packet = 1M</code> under both [mysqld] and [mysqldump] </p> <p>to</p> <pre><code>max_allowed_packet = 100M </code></pre>
301,838
0
<p>Not sure if this counts as debugging, but for C and Objective-C code I find the <a href="http://clang.llvm.org/StaticAnalysis.html" rel="nofollow noreferrer">LLVM/Clang Static Analyzer</a> to be invaluable. Helps spot bugs, memory leaks and logical errors even before you see their effects.</p>
10,276,095
0
<p>Yes this is possible, you simply have to specify the transport when initializing the Bus:</p> <pre><code> var config = Configure.With() .SpringBuilder() .AzureConfigurationSource() &lt;--- Don't use this when working on premise. .XmlSerializer() .UnicastBus() .LoadMessageHandlers() .AzureQueuesTransport() &lt;--- Configure Azure Storage Queues .IsTransactional(true) .PurgeOnStartup(false) .InMemorySubscriptionStorage(); </code></pre> <p>For the documentation part, I suggest you take a look on github: <a href="https://github.com/NServiceBus/NServiceBus/tree/master/Samples/Azure" rel="nofollow">https://github.com/NServiceBus/NServiceBus/tree/master/Samples/Azure</a></p> <p>Note that most of these samples are meant to run in Windows Azure, hence the use of the <strong>AzureConfigurationSource</strong>. This won't work when you're running on premise since it uses settings from the RoleEnvironment. Don't use <strong>AzureConfigurationSource</strong> when working on premise.</p>
17,907,540
0
<p>"upload" here <code>$_FILES['upload']</code> refers to the name of the file field in the form.<br> you are only ckecking if a file from the file field named upload has been uploaded <br> <br> did you maybe name the first upload field in the form differently?</p>
35,537,450
0
Rails: define a method to have advanced data from the db <p>I have a model named <code>Category</code>. I also have a model named <code>Todo</code> (in this model there is <code>boolean</code> column <code>completed</code>).</p> <pre><code>Category has_many :todos Todo belongs_to :category </code></pre> <p>I want to print to view all categories and for each category, how many todo are completed and how many are not are completed</p> <p>How can I do this?</p> <p>Thanks!</p>
18,614,756
0
<p>Use the standard vibrate method with patterns parameter</p> <pre><code>public abstract void vibrate (long[] pattern, int repeat) </code></pre> <p>Pass in an array of ints that are the durations for which to turn on or off the vibrator in milliseconds. The first value indicates the number of milliseconds to wait before turning the vibrator on. The next value indicates the number of milliseconds for which to keep the vibrator on before turning it off. Subsequent values alternate between durations in milliseconds to turn the vibrator off or to turn the vibrator on.</p> <p>To cause the pattern to repeat, pass the index into the pattern array at which to start the repeat, or -1 to disable repeating.</p> <p>This method requires the caller to hold the permission VIBRATE.</p> <p>Parameters pattern an array of longs of times for which to turn the vibrator on or off. repeat the index into pattern at which to repeat, or -1 if you don't want to repeat.</p>
19,361,910
0
<blockquote> <p>But is this all the settings can do?</p> </blockquote> <p>Yes, all possible <code>settings</code> are mentioned in <a href="http://underscorejs.org/#template">the docs</a>. You can read the <a href="http://underscorejs.org/docs/underscore.html#section-134">annoted source</a> as well.</p> <blockquote> <p>Can you provide a full list of keys and their meanings for the settings object?</p> </blockquote> <ul> <li><code>interpolate</code>: regex to match expressions that should be interpolated verbatim</li> <li><code>escape</code>: regex to match expressions that should be inserted after being HTML escaped</li> <li><code>evaluate</code>: regex to match expressions that should be evaluated without insertion into the resulting string.</li> <li><code>variable</code>: A variable name to access the data as properties, instead of using a <code>with</code> statement</li> </ul> <blockquote> <p>And is it possible to compile settings into a template?</p> </blockquote> <p>Yes. Simply pass any falsy value (<code>null</code>, <code>undefined</code>, <code>false</code>, …) for <code>data</code> and the method will return a template function instead of rendering it right away.</p>
35,666,712
0
Wix like site builder creation project <p>I am building a system like wix where user will able to create site and connect with their domain. But I am confused about apache configurations and domain mapping. Every users build sites files saved in different directory on server. But how can I configure apache to locate each site directory for each domain? Is it possible to edit apache configuration from php script? Please provide your own opinion….</p>
30,959,005
0
<p>In fact, your question can be merely resolved through an underrated characteristic of <code>box-shadow</code>:</p> <blockquote> <p>The ‘box-shadow’ property attaches <strong>one or more</strong> drop-shadows to the box. The property takes a comma-separated list of shadows, <strong>ordered front to back</strong>. Each shadow is given as a &lt;shadow>, represented by 2-4 length values, an optional color, and an optional ‘inset’ keyword.<br> &lt;shadow&gt; = inset? &amp;&amp; {2,4} &amp;&amp; ?</p> </blockquote> <p>Your current <code>box-shadow: 0 2px 10px 0 rgba(0, 0, 0, 0.16)</code> is <strong>only one</strong> of the possible &lt;shadow&gt;s as stated above.</p> <p>You can simply prepend it with a first (so front) &lt;shadow&gt; with the desired characteristics, like:<br> <code>box-shadow: #fff 0 -5px, 0 2px 10px 0 rgba(0, 0, 0, 0.16)</code>, where the 1st instance has:</p> <ul> <li><code>#fff</code> has to be the same color as the master <code>&lt;ul&gt;</code> color</li> <li><code>0</code> makes no horizontal (right) shadow</li> <li><code>-5px</code>makes a vertical (natively down, but here up since the minus sign) shadow, which is just what you need to hide the top shadow generated by your previous unique (and now 2nd) instance </li> </ul> <p>Then you have to manage with your red <code>&lt;ul&gt;</code> border-bottom, because now it is hidden also: it's up to you to imagine which method to use for that.</p>
10,288,364
0
MySQL Find Full Name Across Two Rows <p>I have a MySQL table where I'm trying to find a person by his full name. The problem is that first and last name are stored on two separate rows in the table as shown here:</p> <pre><code>+-----------------+-------------+-------------+--------------+ | submit_time | form_name | field_name | field_value | +-----------------+-------------+-------------+--------------+ | 1323463601.0947 | Online Form | firstname | Paulo | | 1323463601.0947 | Online Form | lastname | Hill | +-----------------+-------------+-------------+--------------+ </code></pre> <p>How can I construct a query that will get a single result (if possible) by searching for Paulo Hill?</p> <p>Also, the submit_time column should have the same value for both rows--that will be the one column value that is unique in the table.</p>
3,907,633
0
<p>Simply use "where". For instance, to get all the "PassedStudents":</p> <pre><code>var passedStudents = from student in StudentList where student.StatusResult == ResultsStatus.PassedStudent select student; foreach (var student in passedStudents) { Console.WriteLine("[{0}.] {1} passed.", student.Id, student.Detail.Name); } </code></pre> <p>You can also write the query using lambda expressions:</p> <pre><code>var passedStudents = StudentList.Where(student =&gt; student.StatusResult == ResultsStatus.PassedStudent); </code></pre>
23,407,693
0
<p>Apache Storm is a distributed realtime computation system (source: project website.</p> <p>CEP is complex event processing concerned with tracking and analyzing (processing) streams of information (data) about things that happen (events) and deriving a conclusion from them. (Source:wiki)</p> <p>They are two different things. Storm does not itself analyze unless you deploy some code that analyzes. That makes the code doing CEP, and not Storm. You can do CEP using Storm yes, or can do CEP u using JMS or whichever else. </p> <p>Actors such as Akka or Orleans are also candidate places to host event analysis code that does CEP.</p>
24,144,150
0
<p>My take is that <code>__size</code> and <code>__align</code> fields specify (guess what :-) ) the size and alignment of the structure independently of the <code>__data</code> structure. So, the data can be of a less size and have less alignment requirements, it can be modified freely without breaking these basic assumptions about it. And vice-versa, these basic characteristics can be changed without altering the data structure, like <a href="https://sourceware.org/ml/libc-alpha/2003-04/msg00208.html">here</a>.</p> <p>It is important to note that if the size of the <code>__data</code> becomes bigger than specified by <code>__SIZEOF_PTHREAD_MUTEX_T</code>, an assertion fails in <code>__pthread_mutex_init()</code>:</p> <pre><code>assert (sizeof (pthread_mutex_t) &lt;= __SIZEOF_PTHREAD_MUTEX_T); </code></pre> <p>Consider this assertion as an essential part of this approach.</p> <p>So, the conclusion is that this was done not to hide the implementation details, but to make the data structure more predictable and manageable. It is very important for a widely-used library which should care a lot about backward compatibility and performance impact to other codes from the changes which can be made to this structure.</p>
21,695,943
0
checkbox list with filtering jquery -Only need to match first letter <p>i am using <code>check-box list</code> with filtering <code>jquery</code> on a page to populate all the customers name. However, when someone types "A", I only want the names that begin with A to show, not all that included the letter A. How to do this?</p> <pre><code> (function($) { $.widget("ui.checkList", { options: { listItems : [], selectedItems: [], effect: 'blink', onChange: {}, objTable: '', icount: 0 }, _create: function() { var self = this, o = self.options, el = self.element; // generate outer div var container = $('&lt;div/&gt;').addClass('checkList'); // generate toolbar var toolbar = $('&lt;div/&gt;').addClass('toolbar'); var chkAll = $('&lt;input/&gt;').attr('type','checkbox').addClass('chkAll').click(function(){ var state = $(this).attr('checked'); var setState = false; setState = (state==undefined) ? false : true; o.objTable.find('.chk:visible').attr('checked', setState); self._selChange(); }); var txtfilter = $('&lt;input/&gt;').attr('type','text').addClass('txtFilter').keyup(function(){ self._filter($(this).val()); }); toolbar.append(chkAll); toolbar.append($('&lt;div/&gt;').addClass('filterbox').text('filter').append(txtfilter)); // generate list table object o.objTable = $('&lt;table/&gt;').addClass('table'); container.append(toolbar); container.append(o.objTable); el.append(container); self.loadList(); }, _addItem: function(listItem){ var self = this, o = self.options, el = self.element; var itemId = 'itm' + (o.icount++); // generate item id var itm = $('&lt;tr/&gt;'); var chk = $('&lt;input/&gt;').attr('type','checkbox').attr('id',itemId) .addClass('chk') .attr('data-text',listItem.text) .attr('data-value',listItem.value); itm.append($('&lt;td/&gt;').append(chk)); var label = $('&lt;label/&gt;').attr('for',itemId).text(listItem.text); itm.append($('&lt;td/&gt;').append(label)); o.objTable.append(itm); // bind selection-change el.delegate('.chk','click', function(){self._selChange()}); }, loadList: function(){ var self = this, o = self.options, el = self.element; o.objTable.empty(); $.each(o.listItems, function () { console.log(); self._addItem(this); }); }, _selChange: function(){ var self = this, o = self.options, el = self.element; // empty selection o.selectedItems = []; // scan elements, find checked ones o.objTable.find('.chk').each(function(){ if($(this).attr('checked')){ o.selectedItems.push({ text: $(this).attr('data-text'), value: $(this).attr('data-value') }); $(this).parent().addClass('highlight').siblings().addClass('highlight'); }else{ $(this).parent().removeClass('highlight').siblings().removeClass('highlight'); } }); // fire onChange event o.onChange.call(); }, _filter: function(filter){ var self = this, o = self.options, el = self.element; o.objTable.find('.chk').each(function(){ if($(this).attr('data-text').toLowerCase().indexOf(filter.toLowerCase())&gt;-1) { $(this).parent().parent().show(o.effect); } else{ $(this).parent().parent().hide(o.effect); } }); }, getSelection: function(){ var self = this, o = self.options, el = self.element; return o.selectedItems; }, setData: function(dataModel){ var self = this, o = self.options, el = self.element; o.listItems = dataModel; self.loadList(); self._selChange(); } }); })(jQuery); </code></pre> <p>Here is my code.Please can anyone give any suggestion?</p>
30,456,195
0
How to pass multiple parameter on dynamic link function jquery function C#? <p>I have one c# web application in which put one link dynamically like,</p> <pre><code>if (oObj.aData[1] == '2') { Id = oObj.aData[7]; Name = oObj.aData[2]; alert(Name); return '&lt;a href=# onClick="Show(' + Id + ',' + Name + ');"&gt; Show &lt;/a&gt;'; //this is } </code></pre> <p>function like,</p> <pre><code>function Show(id,name) { alert('calling'); } </code></pre> <p>but my function not calling. </p> <p>Is any syntax error or anything else which I forgetting?</p> <p>Please help. </p>
35,230,328
0
<p>If the XML you're trying to parse is what you've posted here, it's invalid since </p> <blockquote> <p>XML documents must contain one root element that is the parent of all other elements:</p> </blockquote> <p><a href="http://www.w3schools.com/xml/xml_syntax.asp" rel="nofollow">http://www.w3schools.com/xml/xml_syntax.asp</a></p> <p>(and yours doesn't, and parsing such string fails with <code>Exception: String could not be parsed as XML in ...</code>).</p> <p>So your XML should be:</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;users&gt; &lt;user&gt; &lt;name&gt; foo &lt;/name&gt; &lt;token&gt; jfhsjfhksdjfhsjkfhksjfsdk &lt;/token&gt; &lt;connection&gt; &lt;host&gt; localhost &lt;/host&gt; &lt;username&gt; root &lt;/username&gt; &lt;dbName&gt; Test &lt;/dbName&gt; &lt;dbPass&gt; 123456789 &lt;/dbPass&gt; &lt;/connection&gt; &lt;/user&gt; &lt;user&gt; ... same structure... &lt;/user&gt; &lt;/users&gt; </code></pre> <p>And you don't need to iterate through the collection</p> <pre><code>// $nodes is SimpleXMLElement $user = $nodes-&gt;user[0]; if($user-&gt;token) return $user-&gt;token-&gt;__toString(); </code></pre>
356,552
0
<p>Per the <a href="http://msdn.microsoft.com/en-us/library/h0hfz6fc.aspx" rel="nofollow noreferrer">MSDN documentation</a> the valid values for mode are:</p> <p><strong>On</strong>: <em>Specifies that custom errors are enabled. If no defaultRedirect attribute is specified, users see a generic error. The custom errors are shown to the remote clients and to the local host.</em> </p> <p><strong>Off</strong> <em>Specifies that custom errors are disabled. The detailed ASP.NET errors are shown to the remote clients and to the local host.</em> </p> <p><strong>RemoteOnly</strong> <em>Specifies that custom errors are shown only to the remote clients, and that ASP.NET errors are shown to the local host. This is the default value.</em> </p> <p>The default is RemoteOnly. </p>
8,303,343
0
<p>Just overcame a similar issue. JBoss 5 and 6 are much more strict with DTD validation than earlier versions, especially the 4.x series. Your <code>jboss.xml</code> file is failing DTD validation, either because element order is incorrect, or there are elements which don't validate against the DTD.</p> <p>Take a look at the order of the XML elements in <code>standardjboss.xml</code>, and you'll see how your <code>jboss.xml</code> file differs.</p>
10,809,079
0
<p>Ok, here's the scoop. QTimer, for reason only known to the designers of QT, inherits the context of the parent of the thread. Not the context of the thread it's launched from. So when the timer goes off, and you send a message from the slot it called, you're not in the thread's context, you're in the parents context.</p> <p>You also can't launch a thread that is child of THAT thread, so that you can fire a timer that will actually be in the thread you want. Qt won't let it run.</p> <p>So, spend some memory, make a queue, load the message into the queue from elsewhere, watch the queue in the thread that owns the TCP port, and send em when ya got em. That works.</p>
11,731,523
0
<p>The TCP protocol described in <a href="http://www.ietf.org/rfc/rfc793.txt" rel="nofollow">RFC 793</a> describes the terms <em>socket</em> and <em>connection</em>. A <em>socket</em> is an IP address and port number pair. A <em>connection</em> is a pair of <em>sockets</em>. In this sense, the same <em>socket</em> can be used for multiple <em>connections</em>. It is in this sense that the <code>socket</code> being passed to <code>accept()</code> is being used. Since a <em>socket</em> can be used for multiple connections, and the <code>socket</code> passed to <code>accept()</code> represents that <em>socket</em>, the API creates a new <code>socket</code> to represent the <em>connection</em>.</p> <p>If you just want an easy way to make sure the one <code>socket</code> that <code>accept()</code> creates for you is the same socket you used to do the <code>accept()</code> call on, then use a wrapper FTW:</p> <pre><code>int accept_one (int accept_sock, struct sockaddr *addr, socklen_t *addrlen) { int sock = accept(accept_sock, addr, addrlen); if (sock &gt;= 0) { dup2(sock, accept_sock); close(sock); sock = accept_sock; } return sock; } </code></pre> <p>If you are wanting a way for a client and server to connect to each other, without creating any more than just one <code>socket</code> on each side, such an API does exist. The API is <code>connect()</code>, and it succeeds when you achieve a <a href="http://stackoverflow.com/questions/5139808/tcp-simultaneous-open-and-self-connect-prevention"><em>simultaneous open</em></a>.</p> <pre><code>static struct sockaddr_in server_addr; static struct sockaddr_in client_addr; void init_addr (struct sockaddr_in *addr, short port) { struct sockaddr_in tmp = { .sin_family = AF_INET, .sin_port = htons(port), .sin_addr = { htonl(INADDR_LOOPBACK) } }; *addr = tmp; } void connect_accept (int sock, struct sockaddr_in *from, struct sockaddr_in *to) { const int one = 1; int r; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &amp;one, sizeof(one)); bind(sock, (struct sockaddr *)from, sizeof(*from)); do r = connect(sock, (struct sockaddr *)to, sizeof(*to)); while (r != 0); } void do_peer (char *who, const char *msg, size_t len, struct sockaddr_in *from, struct sockaddr_in *to) { int sock = socket(PF_INET, SOCK_STREAM, 0); connect_accept(sock, from, to); write(sock, msg, len-1); shutdown(sock, SHUT_WR); char buf[256]; int r = read(sock, buf, sizeof(buf)); close(sock); if (r &gt; 0) printf("%s received: %.*s%s", who, r, buf, buf[r-1] == '\n' ? "" : "...\n"); else if (r &lt; 0) perror("read"); } void do_client () { const char msg[] = "client says hi\n"; do_peer("client", msg, sizeof(msg), &amp;client_addr, &amp;server_addr); } void do_server () { const char msg[] = "server says hi\n"; do_peer("server", msg, sizeof(msg), &amp;server_addr, &amp;client_addr); } int main () { init_addr(&amp;server_addr, 4321); init_addr(&amp;client_addr, 4322); pid_t p = fork(); switch (p) { case 0: do_client(); break; case -1: perror("fork"); exit(EXIT_FAILURE); default: do_server(); waitpid(p, 0, 0); } return 0; } </code></pre> <p>If instead you are worried about performance issues, I believe those worries are misguided. Using the TCP protocol, you already have to wait at least one full round trip on the network between the client and the server, so the extra overhead of dealing with another socket is negligible. A possible case where you might care about that overhead is if the client and server are on the same machine, but even then, it is only an issue if the connections are very short lived. If the connections are so short lived, then it would probably be better to redesign your solution to either use a cheaper communication medium (e.g., shared memory), or apply framing on your data and use a persistent connection.</p>
1,973,823
0
<p>The various <a href="http://en.wikipedia.org/wiki/Central_bank" rel="nofollow noreferrer">Central Banks</a>, for example the <a href="http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html" rel="nofollow noreferrer">ECB</a>, provide Forex rates free to the public.</p> <p>There is a <a href="http://pear.php.net/package/Services/ExchangeRates" rel="nofollow noreferrer">PEAR package for Forex Rates</a> and it is also not hard to code it yourself. Since the data is usually updated on a daily basis, you will want to add caching, so as not to hammer the bank's server.</p> <p>However, if your application is doing any time-critical conversion, you should resort to a commercial service, as these usually update more frequently. I think Yahoo and Google have a financial API and someone already mentioned XE.com.</p>
8,328,932
0
Eclipse toolbar with multiple rows <p>In my RCP app, I contribute several items to the main toolbar. The easy question now is: How do I make Eclipse lay them out so that they appear in a second row, just under the normal toolbar? Or can I add an additional toolbar that appears just under the main bar? Right now, they just appear somewhere between the other items contributed by other plugins. I tried a lot of stuff and searched a long time, couldn't find any answer though.</p>
6,053,897
1
how to assign an sql value to this python variable <p>ok i got this as simple as i can, everythings working and i need one last thing before I'm done with this issue i am using sqlite3 module in python i also have very limited sql expierance</p> <p>the problem- i need to take the only value out of an sql table; the tablename is saves and the row id is 0 the name of the row is lvl. i need to then assign this as the value of the python variable lvl. Then on closure of the program i need to update the sql table with the current value of the python variable lvl (it will take the place of the data i just retrieved--there will also be numerous operations in between).</p> <p>My code for assigning the value of the python Variable</p> <pre><code>conn = sql.connect('databaserm/database') curs = conn.cursor() curs.execute('SELECT 0 FROM saves') lvl = curs.fetchone() conn.commit conn.close() </code></pre> <p>after running this i get the output None</p> <p>and my code for adding data to the database on closure</p> <pre><code> elif choice == q: if choice == q: cn = sqlite3.connect('/databaserm/database') curs = cn.cursor() curs.execute('INSERT INTO saves (lvl) VALUES (?)', lvl) cn.commit cn.close() loop1 = 0 loop = 10000 print "Goodbye!" sys.exit(0) </code></pre> <p>after running this with a preloaded database and the previous code ommited i get a connection error</p> <p>i would be overjoyed at any help i'm offered and hope to work out a solution to this soon </p>
35,674,774
0
<p>Yes this is possible. But one class needs to know the other class. Try it like this:</p> <pre><code>Class1 { public ExampleInstance Instance { get; set; } //Create your Class2 object here with Class2 SecondClassObject = new Class2(this) } Class2 { private Class1 MyCreator; public Class2(Class1 Creator) { this.MyCreator = Creator; } //Now you can use the object with: MyCreator.Instance } </code></pre> <p>Hope this helps.</p>
34,066,504
0
how to create a hover dropdown panel for logout and update profile function? <p>I want to create a yahoo like logout function where in whenever I hover over the username it should display a panel containing logout and update profile function. Currently I am using this code but its not working as expected.</p> <pre><code>&lt;ul&gt; &lt;li class="dropdown"&gt; &lt;a href="#" class="dropdown-toggle" data-toggle="dropdown"&gt;&lt;h1 id="hello"&gt;&lt;em&gt;&lt;?php echo $login_user;?&gt;&lt;/em&gt;&lt;/h1&gt; &lt;b class="caret"&gt;&lt;/b&gt;&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;i class="icon-arrow-up"&gt;&lt;/i&gt;&lt;a href="#"&gt;Logout&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;i class="icon-arrow-down"&gt;&lt;/i&gt;&lt;a href="#"&gt;Update Profile&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>CSS</p> <pre><code>.dropdown-menu a { white-space: normal; left: 1000px; padding-bottom: 100px; } .dropdown-menu &gt; li { position: relative; } .dropdown-menu &gt; li &gt; i { position: absolute; left: 0; top: 3px; } </code></pre>
10,097,651
0
<p>What compiler did you use, I'm willing to bet this worked because whatever compiler you used didn't zero out unused stack variables after a return, you didn't get a seg fault because its still your stack. basically md was left on the stack which you are technically still allowed to address. The difference between the two is </p> <blockquote> <p>largeObj md;</p> </blockquote> <p>is a variable receiving a variable in its entirety.</p> <blockquote> <p>largeObj&amp; mdd = iReturnLargeObjects();</p> </blockquote> <p>is a reference to a variable that due to a lazy compiler still exists.</p>
23,738,860
0
ASP Identity 2.0.0 usermanager calling wrong method? <p>I have implemented a custom UserStore for my ASP MVC project (with Identity 2.0.0, which I use for it allows the use of integer keys).</p> <p>The Usermanager is not custom implemented, but the Microsoft.AspNet.Identity.Usermanager implementation.<br/><br/> When I call: </p> <pre><code>IdentityResult result = await UserManager.CreateAsync(User, model.Password); </code></pre> <p>In my accountcontroller, the </p> <pre><code>public Task UpdateAsync(TUser user) </code></pre> <p>method is called instead of </p> <pre><code> public Task CreateAsync(TUser user) </code></pre> <p>How could this be? Is it a known bug? Could I work around this?</p>
11,721,376
0
<p>For the benefit of other people with the same problem: make sure to use the Visual Studio x64 command prompt for launching the setup script.</p>
936,296
0
Where do you perform your validation? <p>Hopefully you'll see the problem I'm describing in the scenario below. If it's not clear, please let me know.</p> <p>You've got an application that's broken into three layers, </p> <ul> <li>front end UI layer, could be asp.net webform, or window (used for editing Person data)</li> <li>middle tier business service layer, compiled into a dll (PersonServices)</li> <li>data access layer, compiled into a dll (PersonRepository)</li> </ul> <p>In my front end, I want to create a new Person object, set some properties, such as FirstName, LastName according to what has been entered in the UI by a user, and call PersonServices.AddPerson, passing the newly created Person. (AddPerson doesn't have to be static, this is just for simplicity, in any case the AddPerson will eventually call the Repository's AddPerson, which will then persist the data.)</p> <p>Now the part I'd like to hear your opinion on is validation. Somewhere along the line, that newly created Person needs to be validated. You can do it on the client side, which would be simple, but what if I wanted to validate the Person in my PersonServices.AddPerson method. This would ensure any person I want to save would be validated and removes any dependancy on the UI layer doing the work. Or maybe, validate both in UI and in by business server layer. Sounds good so far right? </p> <p>So, for simplicity, I'll update the PersonService.AddPerson method to perform the following validation checks - Check if FirstName and LastName are not empty - Ensure this new Person doesn't already exist in my repository</p> <p>And this method will return True if all validation passes and the Person is persisted, False if Validation fails or if the Person is not persisted.</p> <p>But this Boolean value that AddPerson returns isn't enough for me at the UI layer to give the user a clear reason why the save process failed. So what's a lonely developer to do? Ultimately, I'd like the AddPerson method to be able to ensure what its about to save is valid, and if not, be able to communicate the reasons why it's not invalid to my UI layer.</p> <p>Just to get your juices flowing, some ways of solving this could be: (Some of these solutions, in my opinion, suck, but I'm just putting them there so you get an understanding of what I'm trying to solve)</p> <ul> <li><p>Instead of AddPerson returning a boolean, it can return an int (i.e. 0 = Success, Non Zero equals failure and the number indicates the reason why it failed. </p></li> <li><p>In AddPerson, throw custom exceptions when validation fails. Each type of custom exception would have its own error message. In addition, each custom exception would be unique enough to catch in the UI layer</p></li> <li><p>Have AddPerson return some sort of custom class that would have properties indicating whether validation passed or failed, and if it did fail, what were the reasons</p></li> <li><p>Not sure if this can be done in VB or C#, but attach some sort of property to the Person and its underlying properties. This "attached" property could contain things like validation info </p></li> <li><p><strong>Insert your idea or pattern here</strong></p></li> <li><p><strong>And maybe another here</strong></p></li> </ul> <p>Apologies for the long winded question, but I definately like to hear your opinion on this. </p> <p>Thanks!</p>
23,775,406
0
<p>I'm still not sure if this is doable through the REST endpoint. We've found cases where the SOAP endpoint offers functionality that the REST endpoint does not, and this might be one those cases.</p> <p>What I did was to use the SOAP endpoint instead. There was no built in method for this, so I had to use the general one. That, in this case, was an organization request, where I had se the request name to "AddMemberList".</p>
3,675,782
0
<p>Ok, again I found out some of them:</p> <ul> <li><a href="http://boxcar.io/" rel="nofollow noreferrer">http://boxcar.io/</a></li> <li><a href="http://howlapp.com/" rel="nofollow noreferrer">http://howlapp.com/</a></li> <li><a href="http://prowl.weks.net/" rel="nofollow noreferrer">http://prowl.weks.net/</a></li> </ul>
33,734,349
0
Newline in input filed? <p>I am new to php and never used php. I have one application backend with php. There function for add new text. Its input filed. when I type some text there and if I need some text in new line than its not possible. If I press Enter key for add new line, its saving my data. my code for it like below.</p> <pre><code>public function create() { $this-&gt;set_form_validation_rules(); $data["authors"] = $this-&gt;quotes-&gt;get_authors(); if ($this-&gt;form_validation-&gt;run() == FALSE) { $this-&gt;view("back/create", $data); } else { $this-&gt;quotes-&gt;create(); $this-&gt;redirect_overview(lang("noti_success_added")); } } </code></pre> <p>Please help me for solve issue... Thanks</p>
31,685,741
0
<p>You can create function like this:</p> <pre><code>function changeTemplate($state, template) { return { scope: { 'resource': '=', 'template': '=' }, template: '&lt;div ng-include="{{template}}"&gt;&lt;/div&gt;', link: function (scope) {.... // cool code } } } </code></pre> <p>And just change template argument on parent scope.</p>
37,208,039
0
<p>It seems you are putting the custom property on the log4net.ThreadLogicalContext which is of type DateTime . Why not put it in string format instead of the DateTime type. This make the output a lot easier as trying to add a layout into your configuration.</p>
14,440,353
0
No Known Conversion for SFML Vector2i <p>I'm completely burned out on this one, but why am I getting:</p> <pre><code>client.cpp: In member function 'void Client::netRead(int, int)': client.cpp:158:57: error: no matching function for call to 'Client::nextGameUpdate(sf::Vector2i [0], int [0], sf::IpAddress [0], int&amp;)' client.cpp:158:57: note: candidate is: client.cpp:85:6: note: void Client::nextGameUpdate(sf::Vector2i, int, sf::IpAddress, int) client.cpp:85:6: note: no known conversion for argument 1 from 'sf::Vector2i [0] {aka sf::Vector2&lt;int&gt; [0]}' to 'sf::Vector2i {aka sf::Vector2&lt;int&gt;}' [Finished in 4.7s] </code></pre> <hr> <pre><code> void Client::nextGameUpdate(sf::Vector2i qq, int ww, sf::IpAddress cc, int dataSize) { pListIP[dataSize] = cc; pListVec[dataSize] = qq; pListRot[dataSize] = ww; int num_pListIP = sizeof(pListIP)/sizeof(sf::IpAddress); if (num_pListIP == lastPlayerCount) { return; } else if (num_pListIP &gt; lastPlayerCount) { int new_players = num_pListIP - lastPlayerCount; for (new_players; new_players&gt;0; new_players--) { addPlayer(); } } else if (num_pListIP &lt; lastPlayerCount) { int dc_players = lastPlayerCount - num_pListIP; for (dc_players; dc_players&gt;0; dc_players--) { removePlayer(); } } lastPlayerCount = num_pListIP; } void Client::netRead(int net_step, int dataSize) { sf::Packet player_vectors; sf::Packet player_rotations; sf::Packet player_ips; switch (net_step) { case 1: if (socket.receive(player_vectors, sender, senderPort) != sf::Socket::Done) return; while (dataSize&gt;0) { sf::Vector2i tmp_vec; player_vectors &gt;&gt; tmp_vec.x &gt;&gt; tmp_vec.y; pListVec[dataSize] = tmp_vec; dataSize--; } break; case 2: if (socket.receive(player_rotations, sender, senderPort) != sf::Socket::Done) return; while (dataSize&gt;0) { int tmp_rot; player_rotations &gt;&gt; tmp_rot; pListRot[dataSize] = tmp_rot; dataSize--; } break; case 3: if (socket.receive(player_ips, sender, senderPort) != sf::Socket::Done) return; while (dataSize&gt;0) { std::string tmp_str; player_ips &gt;&gt; tmp_str; sf::IpAddress tmp_ips = tmp_str; pListIP[dataSize] = tmp_ips; dataSize--; } break; } nextGameUpdate(pListVec, pListRot, pListIP, dataSize); } </code></pre> <hr> <p>Header</p> <pre><code>private: sf::Vector2i pListVec[]; sf::IpAddress pListIP[]; int pListRot[]; </code></pre> <p>I feel like it has something to do with the array I'm trying to fill with sf::Vector2i... <em>/me stares blankly at screen</em></p> <p>So very simply put. netRead gets info from another function that is very basic. Then the switch goes through the net_step int...</p> <p>After the game has received all the packets needed to continue, we trigger the nextGameUpdate() and send it 3 arrays and a dataSize int variable.</p> <p>Thanks in advance if you figure this one out. ^^</p>
11,684,553
0
BUG: Recommendations Bar on same page as Facebook Comments <p>I have just added in the new Facebook Recommendations Bar (using the HTML5 version) to a number of blogs and realised that some of them aren't working. After a little digging I managed to pin it down to when I also have the Facebook Comments plugin on the same site. As soon as I comment that out it all works again.</p> <p>The following is being logged in my console 'FB.getLoginStatus() called before calling FB.init()'.</p> <p>None of these sites have anything on the front end we have developed that that use FB.getLoginStatus.</p> <p>Hope this helps to get it resolved quickly.</p> <p>Aran</p>
17,373,613
0
<p>Is <code>MyKey</code> actually immutable?</p> <p>If a key is changed after it has been used in the <code>Multimap</code> (or a <code>HashMap</code>, for that matters), and the change effects <code>hashCode()</code> and <code>equals()</code>, you won't be able to find the associated values anymore: the modified hashcode means the lookup does not happen in the bucket where the values were stored.</p>
15,192,511
0
Why is ngResource modifying saved object to this: g {0: "O", 1: "K", ..} after receiving a response <p>I have a default ngResource defined like this:</p> <pre><code>var Posts = $resource('/posts/'); </code></pre> <p>And after I get one blogpost from my nodejs server like this:</p> <pre><code>$scope.post = Posts.get({_id:query._id}); </code></pre> <p>User makes some changes to it, then I call:</p> <pre><code>$scope.post.$save(); </code></pre> <p>After server returns response code 200, my $scope.post looks like this:</p> <pre><code>g {0: "O", 1: "K", $get: function, $save: function, $query: function, $remove: function, $delete: function} </code></pre> <p>Why? Is there some reason? Should letters "O" and "K" mean that the operation was a success and returned response 200? Would I be able to modify this behaviour without writing my own save method from scratch?</p>
22,250,065
0
The constructor Skin(TextureAtlas) is undefined libgdx <p>I'm coding for android using libgdx but when I try to create a skin using a TextureAtlas, eclipse throws me an error saying to remove argument or change type to FileHandle</p> <pre><code>atlas = new TextureAtlas(Gdx.files.internal("data/packs/button.pack")); skin = new Skin(atlas); </code></pre>
17,807,818
0
Highlight text while playing audio clip in android media player <p>I have a textview in which I have display the lyrics of one audio song &amp; simultaneously i play the audio from raw folder and now I want to highlight the lyrics from textview as per the audio play. So anyone has any idea about this. I have the source code to highlight I just want to find the word palying in audio.</p>
40,923,376
0
<p>You can use regular expressions to match any of the bad words:</p> <pre><code>is_bad = re.search('|'.join(bad_words), bad_string) != None </code></pre> <p><code>bad_string</code> is the string to test, <code>is_bad</code> is <code>True</code> or <code>False</code>, depending on whether <code>bad_string</code> has bad words or not.</p>
12,343,733
0
C++ Simple 0-10 multiplication flashcard using rand() <p>I am having trouble grasping the concept of rand() and srand() in c++. I need to create a program that displays two random numbers, have the user enter a response, then match the response with a message and do this for 5 times. </p> <p>My question is how do I use it, the instructions say I can't use the time() function and that seems to be in every tutorial online about rand().</p> <p>this is what I have so far.</p> <pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; #include &lt;cstdlib&gt; using namespace std; int main() { int seed; int response; srand(1969); seed=(rand()%10+1); cout&lt;&lt;seed&lt;&lt;" * "&lt;&lt;seed&lt;&lt;" = "; cin&gt;&gt;response; cout&lt;&lt;response; if(response==seed*seed) cout&lt;&lt;"Correct!. you have correctly answered 1 out of 1."&lt;&lt;endl; else cout&lt;&lt;"Wrong!. You have correctly answered 0 out of 1."&lt;&lt;endl; </code></pre> <p>This just outputs something like 6*6 or 7*7, I thought the seed variable would be not necessary different but not the same all the time?</p> <p>This is what the output should look like:</p> <pre><code>3 * 5 = 34 Wrongo. You have correctly answered 0 out of 1. 8 * 1 = 23 Wrongo. You have correctly answered 0 out of 2. 7 * 1 = 7 Correct! You have correctly answered 1 out of 3. 2 * 0 = 2 Wrongo. You have correctly answered 1 out of 4. 8 * 1 = 8 Correct! You have correctly answered 2 out of 5. Final Results: You have correctly answered 2 out of 5 for a 40% average. </code></pre> <p>and these are the requirements:</p> <p>Your program should use rand() to generate pseudo-random numbers as needed. You may use srand() to initialize the random number generator, but please do not use any 'automatic' initializer (such as the time() function), as those are likely to be platform dependent. Your program should not use any loops.</p>
8,727,525
0
<p>Both <a href="http://www.h2database.com" rel="nofollow">H2</a> and <a href="http://hsqldb.org/" rel="nofollow">HyperSQL</a> support embedded mode (running inside your JVM instead of in a separate server) and saving to local file(s); these are still SQL databases, but with Hibernate there's not many other options.</p>
31,419,105
0
<p>Java's <code>outputstream</code> can not do what you want either, all it can do is send <code>byte[]</code> which is exactly what C#'s socket classes do.</p> <p>If you want to send complex objects you must use some form of "Serializer" which will let you transform your objects in to a <code>byte[]</code> to be sent out.</p> <p>A easy to use serializer that is built in to .NET is <a href="https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx" rel="nofollow"><code>XmlSeralizer</code></a>, this will produce a string that you can then feed in to a <a href="https://msdn.microsoft.com/en-us/library/system.io.streamwriter(v=vs.110).aspx" rel="nofollow"><code>StreamWriter</code></a> which will convert the string to a <code>byte[]</code> and write it out on to the socket. The other end would just use the reverse process using a <code>StreamReader</code>.</p> <p>If you do not want to use that intermediate text step I would <strong><em>NOT</em></strong> recomend using <a href="https://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter(v=vs.110).aspx" rel="nofollow"><code>BinaryFormatter</code></a> like you see frequently on the internet, it is very "fragil" and having different levels of .NET Windows updates installed on both ends can end up breaking it. Instead I recommend using a 3rd party binary serializer like <a href="https://code.google.com/p/protobuf-net/" rel="nofollow">Protobuf-net</a></p>
33,597,483
0
WPF MVVM ScrollIntoView <p>I have a view with two listboxes:</p> <p>Listbox 1 elements: A, B, C. Listbox 2 elements: ..., A, ..., B, ..., C, ... (long list).</p> <p>When the user selects an element in listbox 1, I want to scroll the same element into view (not select) also in listbox 2.</p> <p>In my viewmodel I have a property bound to the SelectedItem of Listbox 2. But how can I scroll that element into view of listbox 2? Of course I cannot do listbox.ScrollIntoView(selectedItem) in my VM.</p> <p>What's the best solution to solve this problem with the MVVM pattern?</p>
30,441,990
0
ffmpeg recording h264 live stream got error <p>I am trying to record a h.264 live stream using the following code:</p> <pre><code> AVOutputFormat* fmt = av_guess_format(NULL, "test.mpeg", NULL); AVFormatContext* oc = avformat_alloc_context(); oc-&gt;oformat = fmt; avio_open2(&amp;oc-&gt;pb, "test.mpeg", AVIO_FLAG_WRITE, NULL, NULL); AVStream* stream = NULL; ... while(!done) { // Read a frame if(av_read_frame(inputStreamFormatCtx, &amp;packet)&lt;0) return false; if(packet.stream_index==correct_index) { //////////////////////////////////////////////////////////////////////// // Is this a packet from the video stream -&gt; decode video frame if (stream == NULL){//create stream in file stream = avformat_new_stream(oc, pFormatCtx-&gt;streams[videoStream]-&gt;codec-&gt;codec); avcodec_copy_context(stream-&gt;codec, pFormatCtx-&gt;streams[videoStream]-&gt;codec); stream-&gt;sample_aspect_ratio = pFormatCtx-&gt;streams[videoStream]-&gt;codec-&gt;sample_aspect_ratio; stream-&gt;sample_aspect_ratio.num = pFormatCtx-&gt;streams[videoStream]-&gt;codec-&gt;sample_aspect_ratio.num; stream-&gt;sample_aspect_ratio.den = pFormatCtx-&gt;streams[videoStream]-&gt;codec-&gt;sample_aspect_ratio.den; // Assume r_frame_rate is accurate stream-&gt;r_frame_rate = pFormatCtx-&gt;streams[videoStream]-&gt;r_frame_rate; stream-&gt;avg_frame_rate = stream-&gt;r_frame_rate; stream-&gt;time_base = av_inv_q(stream-&gt;r_frame_rate); stream-&gt;codec-&gt;time_base = stream-&gt;time_base; avformat_write_header(oc, NULL); } av_write_frame(oc, &amp;packet); ... } } </code></pre> <p>However, the ffmpeg says </p> <pre><code>encoder did not produce proper pts making some up </code></pre> <p>when the code runs to av_write_frame(); what's the problem here?</p>
15,809,129
1
Error while getting details of the particular system through python script <p>I am using a <a href="http://pastebin.com/RXH4b11v" rel="nofollow noreferrer">script</a> for getting system details. its all working fine in almost 1000 systems, but in one system its getting the below error.</p> <pre><code>File "SystemDetails.py", line 36, in __init__ File "&lt;COMObject WbemScripting.SWbemLocator&gt;", line 5, in ConnectServer File "\\sfs\show_time\Showtime_Package\showtime\Modules\x32\win32com\client\dynamic.py", line 272, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) com_error: (-2147352567, 'Exception occurred.', (0, u'SWbemLocator', u'Not found ', None, 0, -2147217406), None) </code></pre> <p>when i checked the system properties of that system, i found out that only ram is displaying. In rest of the systems both ram and processer information is displayed. for your reference i have attached both system details of my system and the the issue system.</p> <p><img src="https://i.stack.imgur.com/Ygoge.jpg" alt="enter image description here"> <img src="https://i.stack.imgur.com/ewrWL.jpg" alt="enter image description here"></p> <p>Can anyone help me to find out the problem and the solution fot it</p>
18,798,191
0
<p>This is definitely a nasty memory leak. I've <a href="https://code.google.com/p/android/issues/detail?id=60071" rel="nofollow">opened an issue</a> for it since no one else seems to have reported it.</p> <p>Thanks for the "ugly workaround" emmby, that was helpful. A safer approach, although potentially with a performance impact, is to disable URLConnection caching altogether. Since the URLConnection.defaultUseCaches flag is static and, as you might guess, is the default for each instance's useCaches flag, you can just set this to false and no more instances will cache their connections. This will affect all implementations of URLConnection, so it may have farther-ranging effects than desired, but I think it's a reasonable trade-off.</p> <p>You can just create a simple class like this and instantiate it very early in your app's onCreate():</p> <pre><code>public class URLConnectionNoCache extends URLConnection { protected URLConnectionNoCache(URL url) { super(url); setDefaultUseCaches(false); } public void connect() throws IOException { } } </code></pre> <p>The interesting thing is that since this occurs after your app is loaded and run, the system libs should already be cached, and this will only prevent further caching, so this probably gives the best possible trade-off: not caching your apk while allowing the performance benefits of caching the system jars.</p> <p>Before doing this I did modify emmby's solution a bit to make it a standalone class that creates a background thread to periodically clear the cache. And I restricted it to just clear the app's apk, though that can be relaxed if desired. The thing to worry about here is that you're modifying the objects while they may be in use, which is generally not a good thing. If you do want to go this route you just need to call the start() method with a context, e.g. in your app's onCreate().</p> <pre><code>package com.example; import java.lang.reflect.Field; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.jar.JarFile; import java.util.regex.Pattern; import android.content.Context; // hack to remove memory leak in JarURLConnectionImpl // from http://stackoverflow.com/questions/14610350/android-memory-leak-in-apache-harmonys-jarurlconnectionimpl public class JarURLMonitor { private static JarURLMonitor instance; private Pattern pat; private Field jarCacheField; public volatile boolean stop; private static final long CHECK_INTERVAL = 60 * 1000; public static synchronized void start(Context context) { if (instance == null) { instance = new JarURLMonitor(context); } } public static synchronized void stop() { if (instance != null) { instance.stop = true; } } private JarURLMonitor(Context context) { // get jar cache field try { final Class&lt;?&gt; cls = Class.forName("libcore.net.url.JarURLConnectionImpl"); jarCacheField = cls.getDeclaredField("jarCache"); jarCacheField.setAccessible(true); } catch (Exception e) { // log } if (jarCacheField != null) { // create pattern that matches our package: e.g. /data/app/&lt;pkgname&gt;-1.apk pat = Pattern.compile("^.*/" + context.getPackageName() + "-.*\\.apk$"); // start background thread to check it new Thread("JarURLMonitor") { @Override public void run() { try { while (!stop) { checkJarCache(); Thread.sleep(CHECK_INTERVAL); } } catch (Exception e) { // log } } }.start(); } } private void checkJarCache() throws Exception { @SuppressWarnings("unchecked") final HashMap&lt;URL, JarFile&gt; jarCache = (HashMap&lt;URL, JarFile&gt;)jarCacheField.get(null); final Iterator&lt;Map.Entry&lt;URL, JarFile&gt;&gt; iterator = jarCache.entrySet().iterator(); while (iterator.hasNext()) { final Map.Entry&lt;URL, JarFile&gt; entry = iterator.next(); final JarFile jarFile = entry.getValue(); final String file = jarFile.getName(); if (pat.matcher(file).matches()) { try { jarFile.close(); iterator.remove(); } catch (Exception e) { // log } } } } } </code></pre>
25,927,937
0
<p>From Xcode 6.0 UIAlertView class:</p> <blockquote> <p>UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead.</p> </blockquote> <p>On swift ( iOS 8 and OS X 10.10 ), you can do this:</p> <pre><code>var alert = UIAlertController(title: "Alert Title", message: "Alert Message", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Cancel, handler:handleCancel)) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (ACTION :UIAlertAction!)in println("User click Ok button") })) self.presentViewController(alert, animated: true, completion: nil) func handleCancel(alertView: UIAlertAction!) { println("User click cancel button") } </code></pre>
33,876,298
0
Script to be executed in a Div loaded by Ajax <p>I'm using AJAX to load an HTML page inside a <code>div</code>, but this page has scripts that don't work if I load the AJAX code using the click function. The problem is that I need the page to execute the scripts when I click some specific button.</p> <p>The code that works, but load with main page, not when I click the button:</p> <pre><code>$('document').ready(function(){ $.ajax({ url: "primeiro/index.html", }).done(function (data) { $("#curso").html(data); $('#curso').each(function (index, element) { eval(element.innerHTML); }); }); }); </code></pre> <p>I change to this:</p> <pre><code>$('document').ready(function(){ $("#loginsb").click(function () { $.ajax({ url: "primeiro/index.html", }).done(function(data) { $("#curso").html(data); $('#curso').each(function(index, element) { eval(element.innerHTML); }); }); }); }); </code></pre> <p>Then the page seems to be "paused", so, can't load the script.</p> <p>How can I use the click (in <code>#loginsb</code> button) function to load the content inside my <code>div</code>?</p> <p>Thanks!</p>
28,821,333
0
SQL database relational: performance modeling one to many <p>I have got a doubt modeling a relational database. I wonder which option is best in design and performance.</p> <p>First option:</p> <pre><code> Project Project_task Task -------- ----------- ----- id id_project id id_task </code></pre> <p>Second option (my doubt):</p> <pre><code> Project Task -------- ------ id id id_project (INDEX) </code></pre> <p>Note: One project can has got many task, but one task only can has got a project.</p> <p>Maybe the second option is less "relational" but I think it has more performance. I can get all the task of one project quering with a single SELECT without JOIN. I have got a table less than maintaining...</p> <p>Is the second option a good practice and choice?</p>
2,437,421
0
<p>Does your TableAdapter refresh your DataSet? If it does, then you probably have something like a key getting initialized (remember, GUID==good, Int==bad). It's just like when you fill from a TableAdapter you need to call AcceptChanges to reset the state of all of the rows to unchanged.</p>
33,103,263
0
Android MediaPlayer with LocalSocket not working <p>I am trying to play media from LocalSocket using MediaPlayer. The stream is of type MPEG-TS, which is availale in a LocalSocket input stream</p> <p>Following code tries to <code>setDataSource</code> to the <code>FileDescriptor</code> of <code>LocalSocket</code>, but failes.</p> <pre><code>LocalSocket wsIns = fileThread.getReadSocket(); p = new MediaPlayer(); p.setDisplay(holder); FileDescriptor fd = wsIns.getFileDescriptor(); Log.e("TS","is valid ? "+fd.valid()); p.setDataSource(fd ,0, fileThread.getLength()); </code></pre> <p>setDataSource fails with following exception.</p> <pre><code>10-13 17:21:31.510: W/System.err(6472): java.io.IOException: setDataSourceFD failed.: status=0x80000000 10-13 17:21:31.510: W/System.err(6472): at android.media.MediaPlayer.setDataSource(Native Method) 10-13 17:21:31.510: W/System.err(6472): at com.example.test.TSRenderActivity.surfaceCreated(TSRenderActivity.java:94) </code></pre> <p>The debug logs suggest that the error is primarily due to <a href="http://androidxref.com/4.1.2/xref/frameworks/av/media/libmediaplayerservice/MediaPlayerService.cpp#835" rel="nofollow">this</a>, where <code>fstat</code> on the LocalSocket's file descriptor returns size of the file as 0.</p> <p>But if I try <code>wsIns.getInputStream().available()</code> this api gives non zero number of bytes available.</p> <p>Note : The same error on using <code>p.setDataSource(fp);</code></p>
26,155,209
0
<p>This is to demonstrate HA functionality, so that users can try this on their local machine, Do use the appropriate machine host/ips and ports when appropriate. </p> <p>Suho </p>
1,805,871
0
<p>I think that you need to use the order table instead of the order view to do this.</p>
13,340,905
0
<pre><code>var re = /(#{5})/; console.log ("&lt;foo&gt;\n&lt;bar&gt;\n#####&lt;foo&gt;\n#####&lt;bar&gt;".match (re)); console.log ("&lt;foo&gt;\n&lt;bar&gt;\nfoo&gt;\n&lt;bar&gt;".match (re)); </code></pre> <p>output:</p> <pre><code>[ '#####', '#####', index: 12, input: '&lt;foo&gt;\n&lt;bar&gt;\n#####&lt;foo&gt;\n#####&lt;bar&gt;' ] null </code></pre> <p>If it's optional the regexp fails when there's no match and if it fails it returns null.</p> <pre><code>&gt; /a/.exec("a") [ 'a', index: 0, input: 'a' ] &gt; /a/.exec("b") null &gt; "a".match(/a/) [ 'a', index: 0, input: 'a' ] &gt; "b".match(/a/) null </code></pre> <p>Also, don't use String#match(), it's slower than RegExp#exec() and both return the same:</p> <p><a href="http://jsperf.com/string-match-vs-regexp-test/3" rel="nofollow">match() vs exec()</a></p>
25,867,231
0
<p>Here is solution using transforming string to XML which brings more freedom with result processing:</p> <pre><code>-- Prepare data for solution testing DECLARE @srctable TABLE ( Id INT, SnmpMessage VARCHAR(MAX), SnmpMessageXml XML ) INSERT INTO @srctable SELECT Id, SnmpMessage, SnmpMessageXml FROM ( VALUES (1, 'community=PUBLIC, enterprise=1.1.1.1.1.1.1.1.1.1.1, uptime=42170345, agent_ip=1.1.1.1, version=Ver2', null) ) v (Id, SnmpMessage, SnmpMessageXml) -- Transform source formatted string to XML string UPDATE @srctable SET SnmpMessageXml = CAST('&lt;row&gt;&lt;data ' + REPLACE(REPLACE(SnmpMessage, ',', '"/&gt;&lt;data '), '=', '="') + '"/&gt;&lt;/row&gt;' AS XML) -- Final select from XML data SELECT SnmpMessageXml.value('(/row/data/@community)[1]', 'VARCHAR(999)') AS community, SnmpMessageXml.value('(/row/data/@enterprise)[1]', 'VARCHAR(999)') AS enterprise, SnmpMessageXml.value('(/row/data/@uptime)[1]', 'VARCHAR(999)') AS uptime, SnmpMessageXml.value('(/row/data/@agent_ip)[1]', 'VARCHAR(999)') AS agent_ip, SnmpMessageXml.value('(/row/data/@version)[1]', 'VARCHAR(999)') AS version FROM @srctable AS t </code></pre>
40,434,977
0
IPSEC is Creating Multiple SAD's at rekeying in phase2 <p>I am trying to create a tunnel between two peers with ipsec.while establishing the tunnel at first time, the number of sad(inbound &amp; outbound) entries are as per number of peers. Once after reaching to soft limit of ipsec timer it is starting the re-negotiation to create new sad's, but it is not creating entries as per number of peers, it is negotiating &amp; creating multiple sad entries until the timer reaches to Hard limit.</p> <pre><code>Example:- #setkey -D | grep diff diff:65 Hard:1000 soft:800 </code></pre> <p>In between Soft to Hard limit, it is negotiating &amp; creating multiple sad entries, sometimes my data is also not transferring from my site to peer site but timers are in active.</p> <p>For this i have checked with versions from ipsec-tools-0.7.2 to ipsec-tools-0.8.2, i have checked all versions in between them &amp; i am using linux kernel 2.6.11.</p> <p>can any one tell me, what is the limit or how many it has to create while rekeying, otherwise why this many sad entires are being created.</p>
18,624,227
0
<p><code>message.getBytes()</code> in your case is trying to convert Chinese Unicode characters to bytes using the default character set on your computer. If its a western charset, its going to be wrong.</p> <p>Notice that <code>String.getBytes()</code> has another form with <code>String.getBytes(String)</code> where the string is the name of a character encoding that is used to convert the chars of the string to bytes.</p> <p>The <code>char</code> type will hold Unicode. The <code>byte</code> type only holds raw bits in groups of 8.</p> <p>So, to convert a Unicode string to bytes encoded as UTF-16 you would use this code:</p> <pre><code>String message =" 汉语"; byte[] utf16Bytes = message.getBytes("utf-16"); </code></pre> <p>Substitute the name of any encoding that you want to use.</p> <p>Similarly <code>new String(String, byte[])</code> constructor can take an array of bytes encoded in some fashion and, given the String, can convert those bytes to Unicode characters.</p> <p>For example: If you want to convert those bytes, which were encoded as utf-16 above, back to a <code>String</code> (which has Unicode <code>char</code>s in it):</p> <pre><code>String newMessage = new String(utf16Bytes, "utf-16"); </code></pre> <p>Since I don't know what you mean by "binary code" above, I can't go much farther. As I see it, the Unicode chars have a binary code inside them that represents the characters one-by-one. Also the byte array has a binary code in it that represents the characters with a many-bytes-to-one-character representation. If you want to encrypt the byte array somehow, use a standard, proven encryption method and proven, time-tested procedures to secure the contents.</p>
11,465,707
0
<p>I ran your code and I got this error: XMLHttpRequest cannot load <a href="http://api.jquery.com/get/" rel="nofollow">http://api.jquery.com/get/</a>. Origin null is not allowed by Access-Control-Allow-Origin.</p> <p>I googled it and I got this: <a href="http://stackoverflow.com/questions/8456538/origin-null-is-not-allowed-by-access-control-allow-origin">Origin null is not allowed by Access-Control-Allow-Origin</a></p>
6,145,644
0
<p>Try this to force correct detection of the charset:</p> <pre><code>$doc = new DOMDocument(); @$doc-&gt;loadHTML('&lt;?xml encoding="UTF-8"&gt;' . $html); $nodes = $doc-&gt;getElementsByTagName('title'); $title = $nodes-&gt;item(0)-&gt;nodeValue; echo $title; </code></pre>
34,364,188
0
<p>Assuming you want to add the result <code>z</code> from each method:</p> <pre><code>static int number1(){ int x, y, z; x=2; y=2; z=x+y; return z; } static int number2(){ int x, y, z; x=3; y=2; z=x+y; return z; } </code></pre> <p>You could simplify this though to a more generic method:</p> <pre><code>static int adder(int a, int b) { return a + b; } public static void main (String [] args){ p = adder(2, 2) + adder(3, 2); } </code></pre>
6,105,179
0
Generate AST for Java with ANTLR <p>As far as I know, there are two mechanisms in ANTLR for building abstract syntax trees. I want to build a AST for Java source files.</p> <p>Question: There are so many grammar rules in Java.g (java specification), it's a large work if I specify the AST generating rules for every item in Java.g. So I wondering if there is a ready-made one, and where can I get it.</p>
3,641,409
0
<p>Check here: <a href="http://jsfiddle.net/uh2Gn/" rel="nofollow noreferrer">http://jsfiddle.net/uh2Gn/</a></p> <p>HTML:</p> <pre><code>&lt;form method="post" enctype="" onsubmit="return validate()"&gt; &lt;input type="file" id="file" /&gt; &lt;input type="submit" /&gt; &lt;/form&gt; </code></pre> <p>JavaScript:</p> <pre><code>function validate() { var filename=document.getElementById('file').value; var extension=filename.substr(filename.lastIndexOf('.')+1).toLowerCase(); //alert(extension); if(extension=='jpg' || extension=='gif') { return true; } else { alert('Not Allowed Extension!'); return false; } } </code></pre> <p>Keep in mind that this is only for user convenience, that he doesn't go theu a long submit process to get an error at the server, cuz for sure you <em>must</em> implement a check at server-side.</p>
31,561,644
0
Why doesn't this function load after a successful ajax call in jquery? <p>I'm using <a href="http://papermashup.com/parse-xml-with-jquery/" rel="nofollow">the tutorial here</a>, that used to work last month, but now it isn't. I've copied the relevant code below.</p> <pre><code>$(document).ready(function () { $.ajax({ type: "GET", url: "http://papermashup.com/demos/jquery-xml/books.xml", dataType: "xml", success: xmlParser }); alert("123"); }); function xmlParser(xml) { alert("456"); $('#load').fadeOut(); $(xml).find("Book").each(function () { $(".main").append('&lt;div class="book"&gt;&lt;div class="title"&gt;' + $(this).find("Title").text() + '&lt;/div&gt;&lt;div class="description"&gt;' + $(this).find("Description").text() + '&lt;/div&gt;&lt;div class="date"&gt;Published ' + $(this).find("Date").text() + '&lt;/div&gt;&lt;/div&gt;'); $(".book").fadeIn(1000); }); } </code></pre> <p>The problem is that the xmlParser() function isn't being called after the successful ajax request. It shows a 123 alert but not a 456 alert. Am I doing something wrong, or is the tutorial wrong?</p> <p>I've included a relevant jsfiddle here. <a href="http://jsfiddle.net/desbest/nwt3unxu/" rel="nofollow">http://jsfiddle.net/desbest/nwt3unxu/</a></p>
9,040,800
0
<p>You are creating an array that is too small for the loop. Namely: <code>new char[28][31];</code> will only allow for a maximum index of 27 and 30. Your for loops are:</p> <pre><code>for (int i=0; i&lt;=31; i++) for (int y=0; y&lt;=28; y++) </code></pre> <p>Use <code>i&lt;31</code> and <code>y&lt;28</code>, or increase your array to be <code>[29][32]</code>. Either one of these should solve your current problem.</p>
21,509,019
0
<p>You're on the right track using dimensions. Make a different <code>values</code> folder for each screen size you'd like to support, ie <code>values-sw320dp</code>, <code>values-sw600dp</code>, etc. Each with its own dimens.xml file. Then, put different values for leftMargin, topMargin, etc in each dimens file. Look at the section "Using new size qualifiers" <a href="http://developer.android.com/guide/practices/screens_support.html" rel="nofollow">here</a> for more info.</p>
31,466,863
0
<p>Your mistake is here:</p> <pre><code>while(right-&gt;next != NULL){ right = right-&gt;next; } </code></pre> <p>You are trying to check "right->next" where "right" is NULL.</p>
7,437,766
0
Help me understand this algorithm (simple) <p>I have just made a queue class and I now have to use it to do this.</p> <p>Write a c++ program to generate all strings using A,B,and C as the letters.</p> <p>The strings must be generated in the following order: A B C AA AB AC BA BB BC CA CB CC AAA AAB AAC ABA ABB ABC ACA ACB ACC etc.</p> <p>It's supposed to do this until my queue overflows.</p> <p>Now, I simply don't understand the algorithm the teacher suggested using, which is this.</p> <p><strong>Start with A and B and C in the queue. “Remove it Display it then Add Add Add ”</strong> </p> <p>The add add add thing throws me off, how does it accomplish getting these letters in this particular order?</p>
16,022,969
0
<p>Monocross development has not been halted. It is still under active development, the team that released the Monocross cross-platform framework has been hard at work on <a href="http://ifactr.com" rel="nofollow">iFactr</a>, their enterprise level UI abstraction layer with data cache and queue.</p> <p>They just announced a recommitment to the open source community on Xamarin's cross-platform forums.</p>
15,843,242
0
<p>Easy with do-while:</p> <pre><code>Scanner keyboard = new Scanner(System.in); int startr, endr; boolean good = false; do { System.out.println("Enter the Starting Number of the Range: "); startr = keyboard.nextInt(); if(startr % 10 == 0 &amp;&amp; startr &gt;= 0) good = true; else System.out.println("Numbers is not divisible by 10"); } while (!good); good = false; do { System.out.println("Enter the Ending Number of the Range: "); endr = keyboard.nextInt(); if(endr % 10 == 0 &amp;&amp; endr &lt;= 1000) good = true; else System.out.println("Numbers is not divisible by 10"); } while (!good); // do stuff </code></pre>
32,722,441
0
Finding a single, or multiple values from a string of arrays in Javascript <p>I'm trying to search through my array for whatever number I put in, but it doesn't work as intended. </p> <p>In external javascript:</p> <pre><code>window.onload = startup; function startup() { runArraySequence () { writeArray.onclick = findArray; } } var array = [5,3,9,12,19,15,13,6,9,2,4,7,8,17]; function findArray () { //The following script is a part of a 12 "else if" radio button form. if (arrayRad11.checked) { var searchNumber = document.getElementById("arrayValue").value; var arrayResult = -1; for (var i=0; i &lt; array.length; i++) { if (array[i] === searchNumber) { i = arrayResult; } if (arrayResult &lt; 0) { msg6.innerHTML = "Found number " + searchNumber + ", " + arrayResult + " times."; } } } } </code></pre> <p>HTML code:</p> <pre><code>&lt;div&gt; &lt;form&gt; &lt;input type="radio" id="arrayRad11" name="array" value="11"&gt;Find Number:&lt;/input&gt; &lt;input type="number" id="arrayValue" placeholder="Find Array Number"&gt;&lt;/input&gt;&lt;br /&gt; &lt;input type="button" id="writeArray" value="Skriv tall"&gt;&lt;/input&gt; &lt;input type="button" value="Reset" onClick="window.location.reload()"&gt;&lt;/input&gt; &lt;/form&gt; &lt;p id="msg6"&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p>Also uploaded to <a href="http://jsfiddle.net/v48am4jo/5/" rel="nofollow">jsfiddle</a></p>
14,812,532
0
<p>The <code>develop</code> command wants to add a <code>.pth</code> entry for your project so that it can be imported as an egg. See the <a href="http://pythonhosted.org/setuptools/setuptools.html#development-mode" rel="nofollow">Development mode documentation</a>, as well as the <a href="http://pythonhosted.org/setuptools/setuptools.html#develop" rel="nofollow"><code>develop</code> command docs</a>.</p> <p>The default is to put that entry in site-packages. Set a different library path with the <code>--install-dir</code> switch.</p>
21,900,487
0
Acessing activity data from custom button <p>In my Android activity I have created members which I want to access from my custom button created dynamically. Is there a mechanism to do this? Thanks in advance.</p>
13,285,184
0
In Scala, what's the most idiomatic way to name the case class equivalent of an ORM class? <p>I have to work with Lift's Mapper (I know there might be better ORMs for Scala, but this is not something I have the power to change right now). Typically, with Mapper, a table is defined this way:</p> <pre><code>package com.sample.model import net.liftweb.mapper._ class Table extends LongKeyedMapper[Table] with IdPK { def getSingleton = Table object other_table_id extends MappedLongForeignKey(this, OtherTable) object date_field extends MappedDate(this) object string_field extends MappedString(this, 255) def toCaseClass = ... } object Table extends Table with LongKeyedMetaMapper[Table] </code></pre> <p>Now I'd like to define a case class for Table to manipulate the records more easily, as Mapper is not very "Scala-idiomatic", not very type-safe, and definitely not immutable. My case class would look like this:</p> <pre><code>case class TableCC(id: Long, otherTableId: Long, dateField: Option[Date], ...) { def toMapper = ... } </code></pre> <p>How should I name the case class and where should I put it?</p> <ol> <li>In com.sample.model with a different name (TableCC or TableCaseClass)?</li> <li>In a different packagge (e.g. com.sample.model.caseclass) with the same name (Table)?</li> <li>In the Table object?</li> <li>...?</li> </ol>
14,715,703
0
<p>you may use something like:</p> <p><code>var list = variants[stringToGetCorrespondingList]</code></p>
30,540,893
0
<p>In that case you should be performing a <code>LEFT JOIN</code> instead like</p> <pre><code>SELECT SH1.[Sticker Price], SH1.[Credit Price], SH1.[Cash Price], SH1.[Credit Price], UG.Description as Value, CASE ROW_NUMBER() OVER(ORDER BY UG.Description) WHEN 1 THEN 1 ELSE 0 END as ISDEFAULT FROM [uStore].[dbo].[ACL_UserGroup] UG LEFT JOIN [uStore].[dbo].[ACL_UserGroupMembership] UGM ON UG.UserGroupId = UGM.UserGroupId LEFT JOIN [XMPDBHDS].[XMPieHDSSchema60].[Sheet1] SH1 ON CONVERT(nvarchar(100), SH1.[Centre Code]) = UG.Description WHERE UGM.UserId = 1012 AND SH1.[Credit Price] IS NOT NULL AND UGM.UserGroupId IS NOT NULL; </code></pre>
39,071,641
0
<p>I see you found your solution, but for other's where this continues I had the same problem, until I simply 1. ran</p> <pre><code>adb wait-for-device </code></pre> <ol start="2"> <li>reconnected the device via usb</li> <li>changed "Use USB for" "File Transfers"</li> </ol>
24,646,887
0
convert a MQLONG value to string in c++ <p>How can I print a IBMMQ MQLONG value in c++ code. It gives a segmentation fault when I try to print</p> <pre><code>printf("Queue Persistance-&gt; %s\n ", pMsgDesc -&gt; Persistence ); </code></pre> <p>Thanks</p>
32,784,318
0
Add thread into thread array <p>Take a look at my code.</p> <pre><code>Thread[] connect_thread; public void thread_runned() { connect_thread = new Thread[dataGridView1.SelectedRows.Count]; for (int index = 0; index &lt; dataGridView1.SelectedRows.Count; index++) { connect_thread[index] = new Thread(new ThreadStart(connect)); connect_thread[index].Start(); } } public void connect() { //performance code here } public void ButtonClick1() { //User select rows 0-4 thread_runned(); } public void ButtonClick2() { //User select rows 5-9 thread_runned(); } </code></pre> <p>According to the code above, when I run it, and click on <code>ButtonClick1</code> and <code>ButtonClick2</code>, it returns two different <code>connect_thread</code>s (see this debug for more detail.)</p> <pre><code>//Debug when ButtonClick1 is running connect_thread = array( [0] = System.Threading.Thread [1] = System.Threading.Thread [2] = System.Threading.Thread [3] = System.Threading.Thread ) //Debug when ButtonClick2 is running connect_thread = Error: Index was outside the bounds of the array. </code></pre> <p>Now, I want to add a new thread item into this thread array, but the indeces must continue like the old thread items (i.e, the next indeces will be <code>[4]</code>, <code>[5]</code>, <code>[6]</code>, etc.)</p> <p>I'm not worrying about this error:</p> <pre><code>//Debug when ButtonClick2 is running connect_thread = Error: Index was outside the bounds of the array. </code></pre> <p>because I can create a list of threads using <code>dataGridView1.Rows.Count</code>, and it will work fine. However, I'm looking to do it the other way other because when the user adds more data into <code>dataGridView</code>, the index will be wrong again.</p> <p>How can I append new threads to the end of my thread array while preserving indeces?</p>
14,603,704
0
<p>If they are for use in template files you can have a look at extract. <a href="http://php.net/manual/en/function.extract.php" rel="nofollow">PHP Manual extract</a>. It will extract all variables from an array into local variables.</p>
2,198,174
0
<p>XML loves recursion. It's a lot of work to lay out the nodes one-by-one or into some gigantic table grid -- your data format is heirarchical and your processing method should be as well.</p> <blockquote> <p>Yep. Tried it. I'm just having trouble getting my mind around the best way to do it. I could use tables. I could use css. Absolute positioning. But nothing I come up with in HTML is really working for me.</p> </blockquote> <p>XSLT is pretty good at transforming xml into html. the following xslt transforms your xml into a series of nested divs and tables. I'm using a table to get each colleague group aligned. seemed like the easiest way. </p> <pre><code>&lt;xsl:template match="employee"&gt; &lt;div class="wrapper"&gt; &lt;div class="smallline" /&gt; &lt;div class="box"&gt; &lt;xsl:value-of select="name"/&gt; &lt;br/&gt; &lt;xsl:value-of select="title"/&gt; &lt;/div&gt; &lt;xsl:if test="directReports/employee"&gt; &lt;div class="smallline"&gt; &lt;/div&gt; &lt;table&gt; &lt;tr&gt; &lt;xsl:for-each select="directReports/employee"&gt; &lt;td&gt; &lt;xsl:apply-templates select="." /&gt; &lt;/td&gt; &lt;/xsl:for-each&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/xsl:if&gt; &lt;/div&gt; &lt;/xsl:template&gt; </code></pre> <p>To preview, save the xslt from <a href="http://pastebin.com/f6597d519" rel="nofollow noreferrer">http://pastebin.com/f6597d519</a></p> <p>Add <code>&lt;?xml-stylesheet href="foo.xslt" type="text/xsl"?&gt;</code> to the top of your employees xml, and open in a browser. In practice, you may want to transform on the server to avoid compatibility issues. To do that in C#, see <a href="http://stackoverflow.com/questions/34093/how-to-apply-an-xslt-stylesheet-in-c">How to apply an XSLT Stylesheet in C#</a></p>
34,166,812
0
Hibernate/JPA: only one entry can have specific field value <p>I need something that seems not so specific but anyway I was unable to come up with nice and sophisticated solution.</p> <p>Say I have very simple hibernate/jpa entity:</p> <pre><code>@Entity(name="entity") public class Type { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @Column(unique = true, nullable = false) private String name; @Column(unique = false, nullable = false) private boolean defaultType; } </code></pre> <p>What i need is to somehow annotate <em>defaultType</em> field so only (and exactly) one persisted entity have this value as true. When new entity get persisted with this <em>defaultType</em> as true, the old one (with <em>defaultType</em>=true) entity has to be altered and its <em>defaultType</em> value changed to false. Also if any entity get changed (its <em>defaultType</em> got changed to true), same rule should apply.</p> <p>As far I know this can be achieved inside business logic (e.g. in DAO layer), with DB trigger or with hibernates interceptor or event (If there is another way, please let me know). I tried with DAO solution but it's kind of bad solution because it can be bypassed and it is really clumsy for such simple operation. DB triggers can not be added with hibernate/jpa annotations (if I am not mistaken) and i am not sure how to make this functionality with hibernate interceptors/events.</p> <p>So, what is best solution for this problem?</p>
38,370,714
0
jbehave override scenario failure strategy <p>I have jbehave configured to execute stories via embeddable class that is extended from JUnitStories via maven goal "run-stories-as-embeddables'.</p> <p>I'm trying to achieve the following: I would like not to fail maven goal in case scenario fail was caused by known bug in the system. I've already have mechanism of defining whether this scenario has known opened bug. What is unknown is how to make jbehave not to fail maven goal in case of failure in scenario. Would appreciate any help!.</p>
21,475,943
0
Not able to set compression mode to JPEG-LS in JAI <p>I am using JAI 1.1.3 for windows and configured Build path to include jai_codec , jai_core and jai_imageio jars. When i try to write a image with JPEG-LS mode i get the error. Do i need to do any other configuration for JAI.</p> <pre><code> import java.awt.image.renderable.ParameterBlock; import java.io.IOException; import javax.media.jai.JAI; import javax.media.jai.PlanarImage; public class JpegLs { public static void main(String args[]) throws IOException{ float x =0; float y =0; float width =100; float height =100; PlanarImage input = JAI.create("fileload", "bear.jpg"); ParameterBlock pb = new ParameterBlock(); pb.addSource(input); pb.add(x); pb.add(y); pb.add(width); pb.add(height); PlanarImage output = JAI.create("crop",pb,null); JAI.create("filestore",output,"abc.jpg","JPEG-LS"); } } </code></pre> <p>I am getting the following error</p> <pre><code>Exception in thread "main" java.lang.IllegalArgumentException: FileStore The specified format has no associated registered ImageCodec. at javax.media.jai.JAI.createNS(JAI.java:1087) at javax.media.jai.JAI.create(JAI.java:973) at javax.media.jai.JAI.create(JAI.java:1621) at Sequence.Jai.main(Jai.java:25) </code></pre>
5,792,952
0
how to read and edit .resx file <p>hey guys, i have an asp.net website. which has resource file, which contains a key known as <code>ControlTitle_userarticlemanage.Text</code> whose value is set to create/edit article. now i want to manage this key at runtime, now there is a page which has edit and add button when user clicks on add the title should be create/edit article else my article...</p> <p>so i want to update the <code>ControlTitle_userarticlemanage.Text</code> key in resx file. Please any one can suggest anything for the same.</p>
3,413,805
0
<p>ARM support both big and little endian. This will most probably be set by the OS so it might be worth while checking this out beforehand.</p> <p>There is also the issue of padding to word size in a struct:</p> <pre><code>struct st { char a; int b; }; </code></pre> <p>will have a <code>sizeof</code> 8 and not the expected 5 bytes. This is so that the int will be word aligned. Generally align everything to 4 bytes and probably use the gcc packed attribute (<code>struct my_packed_struct __attribute__ ((__packed__)) </code>) as well. This will ensure that the internals of the struct are as you expect.</p> <p>Alternatively use the Android Simulator to generate the data file for you.</p>
38,652,756
0
R: Removing unwanted `Variables sorted by number of missings:` from Graph <p>I am using the <code>VIM</code> package in R to plot missing values. I want to sort by number of values in the chart but dont want to see the section <code>Variables sorted by number of missings:</code>. The parameter <code>sortVars=TRUE,</code> is responsible for both the output and the sorting. Its useful for exploratory analysis but i want to use the output in a document using rmarkdown</p> <p>Does anyone know how to implement this. It would be better explained with the code below</p> <pre><code>set.seed(300) Q &lt;- c(1,2,3,4,5,6,NA) mydf &lt;- data.frame(participent = (1:100), A1 = sample(Q,100,replace=TRUE), A2 = sample(Q,100,replace=TRUE), A3 = sample(Q,100,replace=TRUE), B1 = sample(Q,100,replace=TRUE), B2 = sample(Q,100,replace=TRUE), B3 = sample(Q,100,replace=TRUE), C1 = sample(Q,100,replace=TRUE), C2 = sample(Q,100,replace=TRUE), C3 = sample(Q,100,replace=TRUE) ) # Missing Values sorted by volume with unwanted output aggr_plot &lt;- aggr(mydf, col=c('lightgrey','darkgreen'), numbers=FALSE, sortVars=TRUE, combined = TRUE, only.miss = TRUE, labels=names(mydf), cex.axis=.45, plot = TRUE) # Missing Values sorted by volume without unwanted output aggr_plot &lt;- aggr(mydf, col=c('lightgrey','darkgreen'), numbers=FALSE, sortVars=FALSE, combined = TRUE, only.miss = TRUE, labels=names(mydf), cex.axis=.45, plot = TRUE) </code></pre>
34,615,817
0
<p>I got this problem too. It stuck when I ran: "heroku local web -f Procfile.windows" then I try to do it manually like this: "python manage.py runserver 0.0.0.0:5000" and it worked perfectly.</p>
38,466,293
0
<p>Maybe you could do this:</p> <pre><code>tagFile.Save() if(tagFile.Tag.Title == infoVar1) { MessageBox.Show("Tags saved successfully"); } </code></pre> <p>After saving the tags into a file, you can validate with some attribute like Title, album, etc. :)</p> <p>A simple question, which version(of taglib#) are you using?</p>
33,109,962
0
<p>You can do something like this:</p> <pre><code> private void AddHourlyTask(string task) { DateTime expiration = DateTime.Now.AddHours(1); expiration = new DateTime(expiration.Year, expiration.Month, expiration.Day, expiration.Hour, expiration.Minute, expiration.Second, expiration.Kind); OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved); HttpRuntime.Cache.Insert( task, task, null, expiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, OnCacheRemove); } </code></pre> <p>And then in a separate function:</p> <pre><code> public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r) { if (k == "HelloWorld") { Console.Write("Hello, World!"); AddHourlyTask(k); } </code></pre> <p>This would go into your Application_Start() function as:</p> <pre><code>AddHourlyTask("HelloWorld"); </code></pre> <p>In order for this to work, you also need to add this somewhere in your class:</p> <pre><code>private static CacheItemRemovedCallback OnCacheRemove = null; </code></pre> <p>The functions would all sit in your Global.asax.cs file</p>
4,808,890
0
<p>Like Felice (+1) said mocking creates a proxy which means you need to either make things virtual (so Moq can work its proxying magic and override the property).</p> <p>As an alternative if you just want to squirt in a value you can manually stub the class you want to test and expose a means to get at the setter:-</p> <pre><code>public class FooStub : Foo { public SetBar(string newValue) { Bar = newValue; } } </code></pre>
16,012,521
0
<p>Use this custom Spinner class...</p> <pre><code>/** Spinner extension that calls onItemSelected even when the selection is the same as its previous value */ public class NDSpinner extends Spinner { public NDSpinner(Context context) { super(context); } public NDSpinner(Context context, AttributeSet attrs) { super(context, attrs); } public NDSpinner(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void setSelection(int position, boolean animate) { boolean sameSelected = position == getSelectedItemPosition(); super.setSelection(position, animate); if (sameSelected) { // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId()); } } @Override public void setSelection(int position) { boolean sameSelected = position == getSelectedItemPosition(); super.setSelection(position); if (sameSelected) { // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId()); } } } </code></pre>
12,728,552
0
<p>Try to declare tabhost as static and call in child activity as below..</p> <p>Instead <strong>private TabHost tabHost;</strong></p> <p>try <strong>static TabHost tabHost;</strong></p> <p>And in your Child Activity </p> <pre><code> AccidentTabActivity.tabHost.setCurrentTab(2); </code></pre> <p>Then you can set your current tab as you want.</p>
19,008,330
0
How can I best display this nested collection? (Can you tell me why my code isn't working?) <p>Can you tell me why this code isn't working?</p> <p>I have a viewmodel with an observablecollection of searchresults which has an observablecollection of resultproperties. I cannot seem to display the nested collection of result properties like I want.</p> <p>Here are the objects (abstracted for readability):</p> <pre><code>class ViewModel { public ObservableCollection&lt;SearchResults&lt;TDomain&gt;&gt; SearchResults { get; set; } } class SearchResults&lt;TDomain&gt; { public TDomain Result { get; set; } public ObservableCollection&lt;ResultProperty&gt; ResultProperties { get; set; } } class ResultProperty { public string PropertyValue { get; set; } } </code></pre> <p>Here is the xaml I cannot get to work. The DataContext is set to the ViewModel:</p> <pre><code>&lt;StackPanel&gt; &lt;ItemsControl ItemsSource={Binding SearchResults}&gt; &lt;ItemsControl.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;StackPanel&gt; &lt;TextBlock Text={Binding Result.Id}/&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;ItemsControl ItemsSource={Binding ResultProperties}&gt; &lt;ItemsControl.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;TextBlock Text="{Binding PropertyValue}" /&gt; &lt;/DataTemplate&gt; &lt;/ItemsControl.ItemTemplate&gt; &lt;/ItemsControl&gt; &lt;/StackPanel&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;/ItemsControl.ItemTemplate&gt; &lt;/ItemsControl&gt; &lt;TextBlock Text="PLACEHOLDER /////"/&gt; &lt;/StackPanel&gt; </code></pre> <p>The outcome I am looking for is something like this:</p> <pre><code>[Stack panel to keep things orderly] 1 property1property2property3... 2 property1property2property3... 3 property1property2property3... PLACEHOLDER ///// </code></pre> <p>The results I am getting are these</p> <pre><code>[Stack panel to keep things orderly] 1 2 3 PLACEHOLDER ///// </code></pre> <p>In otherwords, the binding isn't picking up the string. I have verified that the collections are populating like expected. But I can't get the xaml to work.</p> <p><em><strong></em>*</strong>*ADDITION INFORMATION</p> <p>Ok, so I tried some of the solutions, but they aren't working so I am going to add more details because maybe I am missing something about how the collections are getting updated.</p> <p>The viewmodel has a button on it called "Search" which uses an ICommand that calls a the view model's TrySearch method which is below:</p> <pre><code>public void TrySearch() { var results = _model.GetAll(); foreach(var result in results) this.SearchResults.Add(new SearchResults&lt;TDomain&gt;(result)); } </code></pre> <p>Could there be a reason this doesn't work because of the way the collection is updated? SearchResults is a dependency property (I know I know, it should be INPC, but its not, its dependency), but the other collections are not. Could this be a problem?</p>
34,078,274
0
Rstudio freezes when loading some packages <p>When i was loading some packages like"rgl", "aplpack", whenever there's gonna be a red stop sign on the right top corner of console window.</p> <p>My Rstudio just freezes, like </p> <p><a href="https://i.stack.imgur.com/MQOsb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MQOsb.png" alt="enter image description here"></a></p> <p>I typed the code like an hour ago, and it is still loading.</p> <p>But other functions work fine. My Rstudio still can run a lot of functions if the red stop sign doesn't need to appear.</p> <p>I have reinstalled Rstudio a lot of times, but it doesn't work. </p>
28,960,063
0
<pre><code>timeit.timeit(stmt='pass', setup='pass', timer=&lt;default timer&gt;, number=1000000) </code></pre> <p>Stupid question, the default number of times the statement is executed is one million... I should have read <code>timeit</code> doc before...</p> <pre><code>&gt;&gt;&gt; timeit.timeit('999 in list(xrange(1000))', number=1) 9.083747863769531e-05 </code></pre>
877,247
0
<p>I've spent some time working on this and came up with this to calculate someone's age in years, months and days. I've tested against the Feb 29th problem and leap years and it seems to work, I'd appreciate any feedback:</p> <pre><code>public void LoopAge(DateTime myDOB, DateTime FutureDate) { int years = 0; int months = 0; int days = 0; DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1); DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1); while (tmpMyDOB.AddYears(years).AddMonths(months) &lt; tmpFutureDate) { months++; if (months &gt; 12) { years++; months = months - 12; } } if (FutureDate.Day &gt;= myDOB.Day) { days = days + FutureDate.Day - myDOB.Day; } else { months--; if (months &lt; 0) { years--; months = months + 12; } days += DateTime.DaysInMonth( FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month ) + FutureDate.Day - myDOB.Day; } //add an extra day if the dob is a leap day if (DateTime.IsLeapYear(myDOB.Year) &amp;&amp; myDOB.Month == 2 &amp;&amp; myDOB.Day == 29) { //but only if the future date is less than 1st March if (FutureDate &gt;= new DateTime(FutureDate.Year, 3, 1)) days++; } } </code></pre>
4,895,469
0
<p>Did you try this ?</p> <pre><code>-o-transform: rotate(270deg); </code></pre>
1,917,990
0
<p>You say that the <code>?</code> is supposed to be for a table name, so you need to provide an actual table name before calling <code>Statement.executeUpdate()</code>. At that point the JDBC driver will tell the database to actually run the statement, so obviously all parameters need to be bound.</p> <p>Maybe you meant to write this:</p> <pre><code>CallableStatement call = jdbcConnection.prepareCall("call sp_msforeachtable(?)"); call.setString(1, "AnActualTableName"); call.executeUpdate(); </code></pre> <p>or maybe you meant to write this:</p> <pre><code>CallableStatement call = jdbcConnection.prepareCall("call sp_msforeachtable(\"ALTER TABLE ? NOCHECK CONSTRAINT all\")"); call.setString(1, "AnActualTableName"); call.executeUpdate(); </code></pre> <p>I'm not sure exactly what <code>sp_msforeachtable()</code> is supposed to do, but I do know that you have to provide values for all parameters before calling <code>executeUpdate()</code></p>