pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
5,888,401
0
<p>I blogged on this. It's not that straight forward and a bit confusing, but simple really.</p> <p><a href="http://a.shinynew.me/post/4641524290/jquery-ui-nested-sortables" rel="nofollow">http://a.shinynew.me/post/4641524290/jquery-ui-nested-sortables</a></p>
1,953,036
0
<p>You can always use a Python property to accomplish your goal:</p> <pre><code>class ClassA(db.Model): name = db.StringProperty() def __get_classBdeleted(self): return self.classB_set.filter('deleted_flag =', 'True') classBdeleted = property(__get_classBdeleted) class ClassB(db.Model): name = db.StringProperty() deleted_flag = db.BooleanProperty() classA = db.ReferenceProperty(ClassA) </code></pre>
35,563,424
0
<p>Try calling</p> <p><code>chart.notifyDataChanged()</code></p> <p>and</p> <p><code>chart.invalidate()</code></p> <p>After setting the offsets.</p>
10,387,135
0
<p>If you want the element to not be visible AND not take in any space you should do:</p> <pre><code>.hidden { display: none; } </code></pre> <p>However if you want to hide the element, but let it take in space you should do:</p> <pre><code>.hidden { visibility: hidden; } </code></pre> <p>See this <a href="http://jsfiddle.net/PeeHaa/gydZV/" rel="nofollow">simple demo</a> for an example.</p> <p>The fact that you think the style is overwritten by the user-agent is that the user-agent doesn't recognize the style you are trying to use (because it is invalid).</p>
24,375,467
0
<p>There are a couple of things here, largely for XML you're going to have to realize that proper XML is organized by a structure of node types. These types and their consistency is defined by the name of the node, so having a different node name for what are essentially the same type, is wrong. Consider this XML:</p> <pre><code>&lt;DocumentElement&gt; &lt;Folders&gt; &lt;Direction Key="folder0"&gt; &lt;question&gt; &lt;ask&gt;Which do you want to go?&lt;/ask&gt; &lt;answer go='folder1'&gt;Go to Left&lt;/answer&gt; &lt;answer go='folder2'&gt;Go to Right&lt;/answer&gt; &lt;/question&gt; &lt;/Direction&gt; &lt;Direction Key="folder1"&gt; &lt;question&gt; &lt;ask&gt;You went left.&lt;/ask&gt; &lt;answer go='finish1'&gt;Go to Finish&lt;/answer&gt; &lt;answer go='finish2'&gt;Go to Finish&lt;/answer&gt; &lt;/question&gt; &lt;/Direction&gt; &lt;/Folders&gt; &lt;Finishers&gt; &lt;finish key="finish1"&gt; &lt;role&gt; &lt;name&gt;Hello World&lt;/name&gt; &lt;description&gt;COOL THING&lt;/description&gt; &lt;/role&gt; &lt;/finish&gt; &lt;finish key="finish2"&gt; &lt;role&gt; &lt;name&gt;FINISH2&lt;/name&gt; &lt;description&gt;COOL THING 2&lt;/description&gt; &lt;/role&gt; &lt;/finish&gt; &lt;/Finishers&gt; &lt;/DocumentElement&gt; </code></pre> <p>Now, I don't fully understand what you are trying to do, so this probably isn't an accurate solution in terms of your <strong>specific</strong> needs, but my goal is to give you an understanding of how Xml works in terms of organizing your data.</p> <p>Your jQuery when using this structure can now be better organized by searching for Keys as attritbutes and node types by their name.</p>
13,390,109
0
iOS 6 CLLocationManager last location <p>So, as of iOS 6, <code>-locationManager:didUpdateToLocation:fromLocation:</code> is deprecated.</p> <p>Apple suggests, instead, using <code>-locationManager:didUpdateLocations:</code>, which provides anywhere from one to a series of recent location changes. However, in the incredibly likely chance it provides a <code>locations</code> array of length 1, there appears to be no way to access the <code>fromLocation:(CLLocation *)oldLocation</code> parameter of old.</p> <p>Is there a way to get at this information without using deprecated methods?</p>
29,108,765
0
How do I AJAX post to an MVC action from within a javascript file? <p>The following code exists in a file called <em>job.js</em>. When I run this code against localhost everything behaves properly. When I do so against my intranet server where there is an application name I get a 404. </p> <pre><code>Job.updateJob = function () { $.post('/Builder/ListJobItems', function (data) { ... }); } </code></pre> <p>I would love to use <code>@Url.Action()</code> but as I said this is javascript (.js) file. I am also aware of the hack where you put a data value onto the body element, but for architectural reasons, I want this code to be decoupled from the DOM. It is a data acquisition engine, why should it even know what a DOM is.</p> <p>I would be fine with a solution that parses <code>window.location</code> in some fashion, but the problem that I am having their is that I need a solution that will work everywhere.</p> <p>What frustrates me most is that I can't see how this isn't a problem everyone would face. Why isn't there a solution? Does everyone just put all of their JavaScript into the razor view? Does no one isolate code into modules anymore? I can't believe either of these is true, and yet there don't seem to be any forth coming solutions for this. I am at a loss.</p>
11,885,973
0
how to automatically make new file with mvim <p>When I run <code>mvim .</code> it opens NERDTree but doesnt open a new file/buffer.</p> <ol> <li><p>How might I accomplish this? Ideally when you type <code>mvim .</code> from terminal it would open MacVim, close NERDtree, and open a new buffer</p></li> <li><p>I'm not sure if this is possible but is there a way that if I run <code>mvim .</code> from the command line multiple times it wouldn't open vim in a new window each time?</p></li> </ol>
13,124,424
0
Include static sitemap in Liferay <p>I'm in need of putting a static <code>sitemap.xml</code> file, because Liferay does not generate all of the desired links, and a few that shouldn't be there. I think it's because it's heavily altered by my <code>ext-plugin</code>. </p> <p>Question is, that is it possible to set up a static <code>sitemap.xml</code>(used by google robots) in the portal root, not being changed by Liferay itself?</p> <p>Using: Liferay 6.0.6</p> <p>Thanks in advance :)</p>
10,725,323
0
<p>Make sure you don't have a space character before or after the entry in the "Work with" field as you try to add the software site.</p> <p>Other than that, the software site is perfectly valid. Perhaps the server was just down at the time you tried it. You could also check to verify that there is no proxy or firewall filtering on your end. Try pinging the site or accessing it in some other way. If Eclipse can't talk to the site, it has no way of knowing that it is valid.</p>
11,995,138
0
<p>I ended up figuring some thing out that would work let me know what you all think.</p> <pre><code>$Des = "c:\test\" $DListFiles = Get-ChildItem $Des -EA 0 Switch($Des) { {!$Des} {$DDE = 4; break} {((Test-Path $Des)-ne $false -and $DListFiles -eq $null)} {$DDE = 1; break} {((Test-Path $Des)-ne $false -and $DListFiles -ne $null)} {$DDE = 2; break} {((Test-Path $Des)-eq $false)} {$DDE = 3; break} } $DDE </code></pre>
28,577,699
0
<p>You don't have to call <code>Flush()</code> on <code>Close()/Dispose()</code>, <code>FileStream</code> will do it for you as you can see from its <em>source code</em>: </p> <p><a href="http://referencesource.microsoft.com/#mscorlib/system/io/filestream.cs,e23a38af5d11ddd3">http://referencesource.microsoft.com/#mscorlib/system/io/filestream.cs,e23a38af5d11ddd3</a></p> <pre><code> [System.Security.SecuritySafeCritical] // auto-generated protected override void Dispose(bool disposing) { // Nothing will be done differently based on whether we are // disposing vs. finalizing. This is taking advantage of the // weak ordering between normal finalizable objects &amp; critical // finalizable objects, which I included in the SafeHandle // design for FileStream, which would often "just work" when // finalized. try { if (_handle != null &amp;&amp; !_handle.IsClosed) { // Flush data to disk iff we were writing. After // thinking about this, we also don't need to flush // our read position, regardless of whether the handle // was exposed to the user. They probably would NOT // want us to do this. if (_writePos &gt; 0) { FlushWrite(!disposing); // &lt;- Note this } } } finally { if (_handle != null &amp;&amp; !_handle.IsClosed) _handle.Dispose(); _canRead = false; _canWrite = false; _canSeek = false; // Don't set the buffer to null, to avoid a NullReferenceException // when users have a race condition in their code (ie, they call // Close when calling another method on Stream like Read). //_buffer = null; base.Dispose(disposing); } } </code></pre>
36,857,917
0
<p>I came with the same problem and my friend I found a quick solution for this.</p> <p>You have to just add a single line before your code.</p> <pre><code>ob_clean(); $ical = "BEGIN:VCALENDAR VERSION:2.0"; </code></pre>
13,879,311
0
<p>OK, lets start from the simplest one (Your first rule):</p> <pre><code>SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer FROM questions q LEFT JOIN answers a ON q.id = a.id WHERE q.asker_username &lt;&gt; 'mikha' GROUP BY q.id,a.username </code></pre> <p>Now lets add Your second rule - now more complexity is added...</p> <pre><code>SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer FROM questions q LEFT JOIN answers a ON q.id = a.id WHERE q.asker_username &lt;&gt; 'mikha' AND q.target_username = 'mikha' OR q.target_username IN ( SELECT username2 FROM connections WHERE username1 = 'mikha' ) GROUP BY q.id,a.username </code></pre> <p>Now the third rule (for everyone answered by mikha):</p> <pre><code>SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer FROM questions q LEFT JOIN answers a ON q.id = a.id WHERE q.asker_username &lt;&gt; 'mikha' AND q.target_username = 'mikha' OR q.target_username IN ( SELECT username2 FROM connections WHERE username1 = 'mikha' ) OR (q.target_username = 'every.one' AND a.username = 'mikha') GROUP BY q.id,a.username </code></pre> <p>Now for the fourth rule:</p> <pre><code>SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer FROM questions q LEFT JOIN answers a ON q.id = a.id WHERE q.asker_username &lt;&gt; 'mikha' AND q.target_username = 'mikha' OR q.target_username IN ( SELECT username2 FROM connections WHERE username1 = 'mikha' ) OR (q.target_username = 'every.one' AND a.username = 'mikha') OR (q.target_username = 'every.one' AND a.username IN ( SELECT username2 FROM connections INNER JOIN answers ON answers.username = connections.username2 AND answers.answers IS NOT NULL WHERE username1 = 'mikha' )) GROUP BY q.id,a.username </code></pre> <p>Fifth rule (Jesus!):</p> <pre><code>SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer FROM questions q LEFT JOIN answers a ON q.id = a.id WHERE q.asker_username &lt;&gt; 'mikha' AND q.target_username = 'mikha' OR q.target_username IN ( SELECT username2 FROM connections WHERE username1 = 'mikha' ) OR (q.target_username = 'every.one' AND a.username = 'mikha') OR (q.target_username = 'every.one' AND a.username IN ( SELECT username2 FROM connections INNER JOIN answers ON answers.username = connections.username2 AND answers.answers IS NOT NULL WHERE username1 = 'mikha' )) OR (q.target_username = 'every.one' AND a.answer IS NULL) GROUP BY q.id,a.username </code></pre> <p>And for the last one: </p> <pre><code>SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer FROM questions q LEFT JOIN answers a ON q.id = a.id WHERE q.asker_username &lt;&gt; 'mikha' AND q.target_username = 'mikha' OR q.target_username IN ( SELECT username2 FROM connections WHERE username1 = 'mikha' ) OR (q.target_username = 'every.one' AND a.username = 'mikha') OR (q.target_username = 'every.one' AND a.username IN ( SELECT username2 FROM connections INNER JOIN answers ON answers.username = connections.username2 AND answers.answers IS NOT NULL WHERE username1 = 'mikha' )) OR (q.target_username = 'every.one' AND a.answer IS NULL) OR (q.target_username = 'every.one' AND a.username NOT IN ( SELECT username2 FROM connections INNER JOIN answers ON answers.username = connections.username2 AND answers.answers IS NOT NULL WHERE username1 = 'mikha' )) GROUP BY q.id,a.username </code></pre> <p>I think that rule 4 and rule 6 are kinda against each other (contradicting could be said) and when used in one query it would have the same effect as if omitted...</p> <p>I didn't test any of the queries but I believe they work.</p>
15,917,460
0
Expand to the largest contained "positioned" block? <p>In a container can you <em>in any way</em> position two blocks <em>above each other</em> (eg absolute) and make the container expand to the size/height of the largest one?</p> <p>If using <code>position: absolute</code> the container does not expand to the size of the positioned element.</p> <p><em>Is there any way to get this effect with CSS?</em></p> <hr> <p>Illustrative (defunct) example:</p> <pre><code>&lt;div class="wrap"&gt; &lt;div class="foo"&gt;foo&lt;/div&gt; &lt;div class="bar"&gt;bar&lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>.wrap{ position: relative; } .foo{ height: 40px; } .bar{ height: 60px; width: 100%; position: absolute; top: 0; left: 0; } </code></pre> <p>jsFiddle: <a href="http://jsfiddle.net/qjFR9/" rel="nofollow">http://jsfiddle.net/qjFR9/</a></p> <p>I'd like to position <code>.bar</code> over <code>.foo</code> (position <code>.bar</code> as if there was no <code>.foo</code>) and <code>.wrap</code> should be the height of the largest child.</p>
37,059,045
0
<p>You can use the OAuth 2.0 API for this. Try <a href="https://developers.google.com/apis-explorer/#p/oauth2/v2/oauth2.tokeninfo" rel="nofollow">tokeninfo in the API Explorer</a>.</p>
12,939,213
0
Trying to generate incremental numbers in a function with foreach <p>This function creates <code>&lt;li&gt;</code> tags and im trying to give each <code>li</code> tag a unique CSS class name, I've tried to create a <code>for</code> loop to generate numbers but this is producing the number 7 rather than counting down to the number 7 in <code>&lt;li&gt;</code> tag. </p> <p>any help greatly appreciated!</p> <pre><code>function the_meta() { if ( $keys = get_post_custom_keys() ) { echo "&lt;ul class='post-meta'&gt;\n"; //tried to add this counter here to generate incremental numbers in the foreach loop for ($i = 0; $i &lt;= 6; $i++) { } foreach ( (array) $keys as $key ) { $keyt = trim($key); if ( is_protected_meta( $keyt, 'post' ) ) continue; $values = array_map('trim', get_post_custom_values($key)); $value = implode($values,', '); echo apply_filters('the_meta_key', "&lt;li class='$i'&gt;&lt;span class='post-meta-key'&gt;$key:&lt;/span&gt; $value&lt;/li&gt;\n", $key, $value); } echo "&lt;/ul&gt;\n"; } } </code></pre>
31,622,387
0
<p>The Streams from the linked answer seem like an analog of core.async channels.</p> <p>Instead of removing all listeners each event maybe pass in a channel that has event details put to it. The same channel should go to the button's logic handler where it will repeatedly be taken from.</p>
14,596,500
0
what are the options for hadoop on scala <p>We are starting a big-data based analytic project and we are considering to adopt scala (typesafe stack). I would like to know the various scala API's/projects which are available to do hadoop , map reduce programs. </p>
7,146,909
0
Validate HTML form with JQuery <p>Can someone see where I'm going wrong with this form validation? I was using an example I found online and it does not work for me. </p> <p>I want to validated the input fields with the jquery before passing it on to the server side script. It supposed to print error message next to the field where the user is missing an input.</p> <p>Here's the code:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Register&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-5"&gt; &lt;link rel="stylesheet" type="text/css" href="style1.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="forms.css" /&gt; &lt;script src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $("#registerform").validate({ rules: { username: "required", firstname: "required", email: {// compound rule required: true, passwd: true, email: true, }, username:{ username: true }, url: { url: true }, comment: { required: true } }, messages: { comment: "Please enter a comment." } }); }); &lt;/script&gt; &lt;style type="text/css"&gt; label { width: 10em; float: left; } label.error { float: none; color: red; padding-left: .5em; vertical-align: top; } p { clear: both; } .submit { margin-left: 12em; } em { font-weight: bold; padding-right: 1em; vertical-align: top; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; Please register below &lt;p /&gt; &lt;form action=" " id="registerform" method="POST"&gt; &lt;table cellspacing="9"&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;Username:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="username" size="30"&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;First name:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="firstname" size="30"/&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;Surname:&lt;/b&gt; &lt;/td&gt;&lt;td&gt;&lt;input type="text" name="lastname" size="30"/&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;Email : &lt;/b&gt; &lt;/td&gt;&lt;td&gt;&lt;input type="text" name="email" size="30"/&gt;&lt;/td&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;Password :&lt;/b&gt; &lt;/td&gt;&lt;td&gt;&lt;input type="password" name="passwd" size="30"/&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;Telephpone:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="telephone" size="30"/&gt;&lt;/td&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;House No:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="ad1" size="30"/&gt;&lt;/td&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;Street Name:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="street" size="30"/&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;Town/ City:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="town" size="30"/&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;Post code:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="pcode" size="30"/&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;p /&gt; &lt;input class="submit" type="submit" value="Sign Up!" /&gt; &lt;input type="reset" value ="Clear Form" onClick="return confirm('Are you sure you want to reset the form?')"&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <p></p> <p>Here's the code the original code that I got from a website somewhere and it works. But I can't seem to use the example in my code.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Simple Form Validation&lt;/title&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $("#form2").validate({ rules: { name: "required",// simple rule, converted to {required:true} email: {// compound rule required: true, email: true }, url: { url: true }, comment: { required: true } }, messages: { comment: "Please enter a comment." } }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form2" method="post" action=""&gt;&lt;br /&gt; Name * &lt;input type="text" name="name" /&gt; &lt;br /&gt; E-Mail *&lt;input type="text" name="email" /&gt; &lt;br /&gt; URL &lt;input type="text" name="url" /&gt; &lt;br /&gt; Your comment * &lt;textarea name="comment" &gt;&lt;/textarea&gt; &lt;br /&gt; &lt;input class="submit" type="submit" value="Submit"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Update:</strong> Thanks to @Usman it's now working. One more question though, is it possible to change the default error message instead of the <strong><em>'This field is required'</em></strong> ?</p> <p>Thanks</p>
570,461
0
<p>Since you're using a <code>TcpClient</code>, that means you're checking open TCP ports. There are lots of good objects available in the <a href="http://msdn.microsoft.com/en-us/library/system.net.networkinformation.aspx" rel="nofollow noreferrer">System.Net.NetworkInformation</a> namespace.</p> <p>Use the <code>IPGlobalProperties</code> object to get to an array of <code>TcpConnectionInformation</code> objects, which you can then interrogate about endpoint IP and port.</p> <hr> <pre><code> int port = 456; //&lt;--- This is your value bool isAvailable = true; // Evaluate current system tcp connections. This is the same information provided // by the netstat command line application, just in .Net strongly-typed object // form. We will look through the list, and if our port we would like to use // in our TcpClient is occupied, we will set isAvailable to false. IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); foreach (TcpConnectionInformation tcpi in tcpConnInfoArray) { if (tcpi.LocalEndPoint.Port==port) { isAvailable = false; break; } } // At this point, if isAvailable is true, we can proceed accordingly. </code></pre>
27,175,544
0
Inno Setup Language Dialog Custom page <p>So, if i can't change Language Dialog, can i create one my custm language dialog?</p> <p>In my installer I have only one custom page, the installation page and at end the finish page.</p> <p>I can put a combo (with 2 language) in my custom page and on change, refresh all label?</p> <p>Thanks</p>
35,165,718
0
<p>I have same issue. Facebook say they are aware of it and its not a high priority as it doesn't affect the app. I regressed back to 4.7.1 where the warning issue is no longer present.</p> <p>I don't think it would be rejected but can't be sure.</p>
37,979,276
0
Google Maps: How to draw labels (country, city names, etc.) over my overlay <p>I need to draw some graphics over google maps. Graphics is not always transparent, so I'd like to draw text labels (country names, city names, etc.) over my graphics.</p> <p>For graphics I use <a href="https://developers.google.com/maps/documentation/javascript/maptypes#OverlayMapTypes" rel="nofollow">overlay map type</a> , it is shown over base map. But I failed to draw labels over it?</p> <p>I guessed that there shall be a way to draw base map twice, with different style settings (so I style map with not labels, put my overlay, and then put overlay with roadmap with labels only), but it does not seem like I can use basic map types as overlay ones. Another way I see is to manually get tile with labels only by composing URL. This works, but as far as I understand accessing map tiles directly is prohibited by ToS.</p> <p>Is there a working and, well, legal way to do that?</p> <p>Here is jsfiddle which illustrates URL composing solution: <a href="https://jsfiddle.net/GRaAL/jyr81p2c/" rel="nofollow">https://jsfiddle.net/GRaAL/jyr81p2c/</a></p> <pre><code>// here is how I get google maps tile with labels only function getLabelsOnlyTile(coord, zoom) { return "https://maps.googleapis.com/maps/vt?pb=!1m5!1m4!1i" + zoom + "!2i" + (coord.x) + "!3i" + (coord.y) + "!4i512!2m3!1e0!2sm!3i353022921!3m14!2sen!3sUS!5e18!12m1!1e47!12m3!1e37!2m1!1ssmartmaps!12m4!1e26!2m2!1sstyles!2zcC52Om9mZixzLmU6bHxwLnY6b24!4e0"; } </code></pre>
34,667,213
0
Validate uniqueness of name in a HABTM association <p>I have an <code>Artist</code> model that has many <code>Album</code>s in a HABTM association. Though I would like to permit two different albums to have the same name I'd like to ensure that there aren't two in the collection of one artist. So far example:</p> <pre><code>artist_1 = Artist.create(name: "Jay-Z") artist_2 = Artist.create(name: "The Beatles") album_1 = Album.create(name: "The Black Album", artist_ids: [1]) album_2 = Album.create(name: "The Black Album", artist_ids: [1]) =&gt; Should return error album_2 = Album.create(name: "The Black Album", artist_ids: [2]) =&gt; Should not return an error </code></pre> <p>I first thought of validating the uniqueness of the name in the <code>Album</code> model but get this error when I try to create a new object:</p> <pre><code>SQLite3::SQLException: no such column: albums.artist_id: SELECT 1 AS one FROM "albums" WHERE ("albums"."name" = 'The Black Album' AND "albums"."artist_id" IS NULL) LIMIT 1 </code></pre> <p>I then thought of putting the validation in my join model, <code>AlbumArtist</code> but get the error <code>undefined method 'name'</code> (<code>name</code> is one of the album's attributes):</p> <pre><code>undefined method `name' for #&lt;AlbumArtist:0x007f8e1fc335e8&gt; </code></pre> <p>How can I get this to work?</p> <pre><code>class Album &lt; ActiveRecord::Base has_many :album_artists has_many :artist, through: :album_artists end class AlbumArtist &lt; ActiveRecord::Base belongs_to :album belongs_to :artist # validates_uniqueness_of :name, scope: [:artist_id] end class Artist &lt; ActiveRecord::Base has_many :album_artists has_many :albums, through: :album_artists # validates_uniqueness_of :name, scope: [:artist_id] end </code></pre> <p><strong>Schema</strong></p> <pre><code>create_table "albums", force: :cascade do |t| t.string "name" end create_table "album_artists", force: :cascade do |t| t.integer "album_id" t.integer "artist_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "album_artists", ["album_id"], name: "index_album_artists_on_album_id" add_index "album_artists", ["artist_id"], name: "index_album_artists_on_artist_id" create_table "artists", force: :cascade do |t| t.string "name" end </code></pre>
11,031,268
0
<p>If you are running Apache with mod_php, you will not see a separate PHP process since the script is actually running inside an Apache process. If you are running as FastCGI, you also might not see a distinguishable PHP process for the actual script execution, though I have no experience with PHP/FastCGI and might be wrong on this.</p> <p>You can set the <a href="http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time" rel="nofollow"><code>max_execution_time</code></a> option, but it is overridable at run time by calling <a href="http://www.php.net/manual/en/function.set-time-limit.php" rel="nofollow"><code>set_time_limit()</code></a> unless you run in <a href="http://www.php.net/manual/en/ini.sect.safe-mode.php#ini.safe-mode" rel="nofollow">Safe Mode</a>. Safe mode, however, has been deprecated in PHP 5.3 and <em>removed</em> in 5.4, so you cannot rely on it if you are on 5.4 or plan to upgrade.</p> <p>If you can manage it with your existing customers (since in some cases it requires non-trivial changes to PHP code), <a href="http://www.php.net/manual/en/install.unix.commandline.php" rel="nofollow">running PHP as CGI</a> should allow you to monitor the actual script execution, as each CGI request will spawn a separate PHP interpreter process and you should be able to distinguish between the scripts they are executing. Note, however, that CGI is the least effective setup (the others being mod_php and FastCGI).</p>
27,722,795
0
How do I use .filter to return multiple values? <p>Say I have a div, with some CSS and javascript:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var someCSS = { color: 'red', }; $(".test &gt; .sub").filter(function(index) { return $(this).text() == 'hello'; }).css(someCSS);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.test { color: green; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div class='test'&gt; &lt;div class='sub'&gt;hello&lt;/div&gt; &lt;div class='sub'&gt;stackoverflow&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>The above will color the 'hello' red, but I don't understand how to add more values, eg 'hello' and 'stackoverflow'. I obviously can't do <code>return $(this).text() == 'hello' || 'stackoverflow';</code>, but I just can't figure out what to do!</p> <p>Any suggestions will be appreciated :)</p>
18,451,644
0
<p><code>!</code> is used to reference one member of a collection ... <code>CollectionName!MemberName</code></p> <p><code>Forms</code> is the name of a collection whose members are <code>Form</code> objects, and includes those forms which are currently open in your Access session.</p> <p>A <code>Form</code> has a collection of <code>Control</code> objects. So appending <code>!ControlName</code> to the form reference gets you a reference to that control.</p> <p>So <code>Forms![HiddenUserCheck]![txtStatus]</code> refers to a control named <em>txtStatus</em> in a form named <em>HiddenUserCheck</em> which is open in your Access session.</p> <p>What you get from that reference is the control's default property, <code>Value</code> ... the value contained in that control.</p>
6,994,397
0
<p>Simple: It does nothing. It doesn't escape anything.<br> Entering \n in a textbox enters two characters. This is different from defining <code>var s = "\n"</code> as this is only one character.</p>
21,443,609
0
Why does `<Button Command={x:Static...}..>` works but `<Button Command={Binding...}..>` doesn't? <p>I'm new to WPF, and I'm trying to implement a custom <code>Command</code>, what I did is that I implemented the <code>ICommand</code> interface and I bound that implementation to a button using two ways one with a Static Extention Marckup and one with a normal Binding, it works fine with <code>{x:Static}</code>, but fails with this error when using <code>{Binding}</code></p> <blockquote> <p>System.Windows.Data Error: 39 : BindingExpression path error: 'StartCommand' property not found on 'object' ''ViewModel' (HashCode=30880833)'. BindingExpression:Path=StartCommand; DataItem='ViewModel' (HashCode=30880833); target element is 'Button' (Name=''); target</p> </blockquote> <p>here is my code</p> <p><strong>XAML</strong></p> <pre><code>&lt;Window x:Class="Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="75" Width="300"&gt; &lt;StackPanel Orientation="Horizontal" Height="30"&gt; &lt;Button Command="{Binding StartCommand}" Content="Start" Margin="5,0"/&gt; &lt;TextBlock Text="{Binding Name}"/&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p><strong>Code behind</strong></p> <pre><code>public partial class Window1 : Window { public Window1() { InitializeComponent(); DataContext = new ViewModel { Name = "Simple property" }; } } class ViewModel { public string Name { get; set; } // static to use with {x:Static} public ICommand StartCommand = new StartCommand(); } class StartCommand : ICommand { public bool CanExecute(object parameter) { return false; } public event System.EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public void Execute(object parameter) { MessageBox.Show("Start Executed"); } } </code></pre> <p>What's wrong with my code? am I messing something? thanks in advance.</p>
16,338,532
0
<p>You can simple use the function <code>stripslashes</code>. </p> <pre><code> stripslashes($string); </code></pre> <p>Have a look into the official <a href="http://ca3.php.net/manual/en/function.stripslashes.php" rel="nofollow">documentation</a></p> <pre><code> &lt;?php $str = "Is your name O\'reilly?"; // Outputs: Is your name O'reilly? echo stripslashes($str); ?&gt; </code></pre>
12,338,452
0
<p>This is very wrong. If you insist on not using <code>strcpy</code> do something like this (not tested)</p> <pre><code>int iStringLength = strlen(name); for (i = 0; i &lt; iStringLength; i++) { s-&gt;name[i] = name[i]; } </code></pre> <p>but make sure that the length is not longer than your array size. </p> <p>This is also wrong</p> <pre><code>Student* makeAndrew(void) { Student s; setName(&amp;s, "Andrew"); setStudentID(&amp;s, 12345678); return &amp;s; } </code></pre> <p>because the <code>s</code> object is destroyed when the function exits - it is local to the function scope and yet you return a pointer to it. So if you try to access the struct using this pointer it will not be valid as the instance no longer exists. If you want to do this you should dynamically allocate it using <code>malloc</code> . Alternatively do not return a pointer at all and use the alternative option of @Andrew .</p>
11,134,020
0
<p>It can be done by getting input and output streams from VFS. The following example uses a utility class from commons-net (a dependency of VFS) to manage the copying and progress-monitoring. You could equally do it manually.</p> <pre><code>import org.apache.commons.net.io.Util; import org.apache.commons.net.io.CopyStreamListener; private void copy(FileObject sourceFile, FileObject destinationFile, CopyStreamListener progressMonitor) throws IOException { InputStream sourceFileIn = sourceFile.getContent().getInputStream(); try { OutputStream destinationFileOut = destinationFile.getContent().getOutputStream(); try { Util.copyStream(sourceFileIn, destinationFileOut, Util.DEFAULT_COPY_BUFFER_SIZE, sourceFile.getContent().getSize(), progressMonitor); } finally { destinationFileOut.close(); } } finally { sourceFileIn.close(); } } </code></pre>
35,969,373
0
All possible combinations of elements in vector with repetitions in MATLAB <p>I have 6 numbers with repetition: 1,2,2,3,3,4. I want all possible combinations using any 4 of the numbers. How will I get that in MATLAB?</p> <p>Generally I use 'nchoosek' function if there is no repetition. </p> <p>Example: <code>A = 1:6; combinations = nchoosek(A,4);</code></p>
27,306,129
0
String inside structure behavior <p>Let's say we have structure</p> <pre><code>struct MyStruct { public string a; } </code></pre> <p>When we assign it to the new variable what will be happened with the string? So for example, we expect that string should be shared when structs are copied in the stack. We're using this code to test it, but it returns different pointers:</p> <pre><code> var a = new MyStruct(); a.a = "test"; var b = a; IntPtr pA = Marshal.StringToCoTaskMemAnsi(a.a); IntPtr pB = Marshal.StringToCoTaskMemAnsi(b.a); Console.WriteLine("Pointer of a : {0}", (int)pA); Console.WriteLine("Pointer of b : {0}", (int)pB); </code></pre> <p>The question is when structs are copied in the stack and have string inside did it share the string or the string is recreated?</p> <p>[UPDATE]</p> <p>We also tried this code, it returns different pointers as well:</p> <pre><code> char charA2 = a.a[0]; char charB2 = b.a[0]; unsafe { var pointerA2 = &amp;charA2; var pointerB2 = &amp;charB2; Console.WriteLine("POinter of a : {0}", (int)pointerA2); Console.WriteLine("Pointer of b : {0}", (int)pointerB2); } </code></pre>
40,810,313
0
JavaScript validating form error message <p>I have been working on this form validation and I got the error message to work when I have it displaying as an alert but I cannot seem to get it to print out with <code>document.getElementById("").innerHTML =</code>.</p> <p>I also have this as the form </p> <pre><code> &lt;form id="form" name="form" method="post" onSubmit="return validate(this) &amp;&amp; reportErrors(errors)" action="&lt;?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?&gt;"&gt; var ck_name = /^(Mr|Mrs)\. (.+)? (.+)?/i; var ck_street = /^[0-9]{2,3} +[a-z A-Z]+ +(Street|Road)$/; var ck_postalInput = /^([D-JL-Wd-jl-w]{2})([1-9]{1})[\-\s]?([D-JL-Wd- jl-w]{1})([1-9]{2})$/; var ck_phoneInput = /^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]* ([\d]{3})[\.\-\s]?([\d]{4})$/; var ck_emailInput =/^[a-zA-Z]+(.)+[a-zA-Z]+(@mohawkcollege)+(.com|.ca|.org)$/; function validate(form){ var nameInput = form.nameInput.value; var streetInput = form.streetInput.value; var postalInput = form.postalInput.value; var phoneInput = form.phoneInput.value; var emailInput = form.emailInput.value; var errors = []; if (!ck_name.test(nameInput)) { errors[errors.length] = "Full name not entered correctly."; } if (!ck_street.test(streetInput)) { errors[errors.length] = "Street name not entered correctly."; } if (!ck_postalInput.test(postalInput)) { errors[errors.length] = "Postal not entered correctly."; } if (!ck_phoneInput.test(phoneInput)) { errors[errors.length] = "Phone number not entered correctly."; } if (!ck_emailInput.test(emailInput)){ errors[errors.length] = "email not entered correctly."; } if (errors.length &gt; 0) { reportErrors(errors); return false; } return true; } function reportErrors(errors){ var msg = "Please Enter Valide Data...\n"; for (var i = 0; i&lt;errors.length; i++) { msg += "\n" + ". " + errors[i]; } document.getElementById("error").innerHtml=msg; } </code></pre>
35,150,355
0
<p>You might be able to use <code>UIManager.put("TabbedPane.contentAreaColor", new Color(255, 255, 0, 100));</code></p> <p><img src="https://i.stack.imgur.com/JGkv4.png" alt="screenshot"></p> <pre><code>import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TransparentTabbedPaneTest { public JComponent makeUI() { Color bgc = new Color(110, 110, 0, 100); Color fgc = new Color(255, 255, 0, 100); UIManager.put("TabbedPane.shadow", fgc); UIManager.put("TabbedPane.darkShadow", fgc); UIManager.put("TabbedPane.light", fgc); UIManager.put("TabbedPane.highlight", fgc); UIManager.put("TabbedPane.tabAreaBackground", fgc); UIManager.put("TabbedPane.unselectedBackground", fgc); UIManager.put("TabbedPane.background", bgc); UIManager.put("TabbedPane.foreground", Color.WHITE); UIManager.put("TabbedPane.focus", fgc); UIManager.put("TabbedPane.contentAreaColor", fgc); UIManager.put("TabbedPane.selected", fgc); UIManager.put("TabbedPane.selectHighlight", fgc); UIManager.put("TabbedPane.borderHightlightColor", fgc); JTabbedPane tabs = new JTabbedPane(); JPanel tab1panel = new JPanel(); tab1panel.setBackground(new Color(0, 220, 220, 50)); JPanel tab2panel = new JPanel(); tab2panel.setBackground(new Color(220, 0, 0, 50)); JPanel tab3panel = new JPanel(); tab3panel.setBackground(new Color(0, 0, 220, 50)); JCheckBox cb = new JCheckBox("setOpaque(false)"); cb.setOpaque(false); tab3panel.add(cb); tab3panel.add(new JCheckBox("setOpaque(true)")); tabs.addTab("Tab 1", tab1panel); tabs.addTab("Tab 2", tab2panel); tabs.addTab("Tab 3", new AlphaContainer(tab3panel)); JPanel p = new JPanel(new BorderLayout()) { private Image myBG = new ImageIcon(getClass().getResource("test.png")).getImage(); @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(myBG, 0, 0, getWidth(), getHeight(), this); } }; p.add(tabs); p.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); return p; } public static void main(String... args) { EventQueue.invokeLater(() -&gt; { JFrame f = new JFrame(); f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); f.getContentPane().add(new TransparentTabbedPaneTest().makeUI()); f.setSize(320, 240); f.setLocationRelativeTo(null); f.setVisible(true); }); } } //https://tips4java.wordpress.com/2009/05/31/backgrounds-with-transparency/ class AlphaContainer extends JComponent { private JComponent component; public AlphaContainer(JComponent component) { this.component = component; setLayout( new BorderLayout() ); setOpaque( false ); component.setOpaque( false ); add( component ); } /** * Paint the background using the background Color of the * contained component */ @Override public void paintComponent(Graphics g) { g.setColor( component.getBackground() ); g.fillRect(0, 0, getWidth(), getHeight()); } } </code></pre>
29,418,705
0
How to change factor to string in R <p>I am working with a data frame that is a list of sequences</p> <pre><code>Alpha_Helix = xmlParse("AlphaTbl.Xml") all_seq = getNodeSet(Alpha_Helix, path = "//Protein/sequence", ) all_seq = xmlToDataFrame(all_seq) </code></pre> <p>I want to find the length of the sequences in each row and then carry out some other work with the sequences but am having trouble accessing them.</p> <p>When I try:</p> <pre><code>length(all_seq$text[1]) [1] 1 nchar(all_seq$text) Error in nchar(all_seq$text) : 'nchar()' requires a character vector nchar(all_seq$text[1]) Error in nchar(all_seq$text[1]) : 'nchar()' requires a character vector as.character(all_seq) # Works [1] "c(117, 91, 8)" </code></pre> <p>How can I access the strings too?</p>
37,579,915
0
Spring MVC + AngularJS + JWT Token Expiration - HowTo <p>I would like to ensure that my JSON Web tokens are revoked/expire after a configurable ammount of time and i have the following set up:</p> <p>Security Filter:</p> <pre><code>import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import yourwebproject2.service.UserService; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; /** * @author: kameshr */ public class JWTTokenAuthFilter extends OncePerRequestFilter { private static List&lt;Pattern&gt; AUTH_ROUTES = new ArrayList&lt;&gt;(); private static List&lt;String&gt; NO_AUTH_ROUTES = new ArrayList&lt;&gt;(); public static final String JWT_KEY = "JWT-TOKEN-SECRET"; static { AUTH_ROUTES.add(Pattern.compile("/api/*")); NO_AUTH_ROUTES.add("/api/user/authenticate"); NO_AUTH_ROUTES.add("/api/user/register"); } private Logger LOG = LoggerFactory.getLogger(JWTTokenAuthFilter.class); @Autowired private UserService userService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String authorizationHeader = request.getHeader("authorization"); String authenticationHeader = request.getHeader("authentication"); String route = request.getRequestURI(); // no auth route matching boolean needsAuthentication = false; for (Pattern p : AUTH_ROUTES) { if (p.matcher(route).matches()) { needsAuthentication = true; break; } } if(route.startsWith("/api/")) { needsAuthentication = true; } if (NO_AUTH_ROUTES.contains(route)) { needsAuthentication = false; } // Checking whether the current route needs to be authenticated if (needsAuthentication) { // Check for authorization header presence String authHeader = null; if (authorizationHeader == null || authorizationHeader.equalsIgnoreCase("")) { if (authenticationHeader == null || authenticationHeader.equalsIgnoreCase("")) { authHeader = null; } else { authHeader = authenticationHeader; LOG.info("authentication: " + authenticationHeader); } } else { authHeader = authorizationHeader; LOG.info("authorization: " + authorizationHeader); } if (StringUtils.isBlank(authHeader) || !authHeader.startsWith("Bearer ")) { throw new AuthCredentialsMissingException("Missing or invalid Authorization header."); } final String token = authHeader.substring(7); // The part after "Bearer " try { final Claims claims = Jwts.parser().setSigningKey(JWT_KEY) .parseClaimsJws(token).getBody(); request.setAttribute("claims", claims); // Now since the authentication process if finished // move the request forward filterChain.doFilter(request, response); } catch (final Exception e) { throw new AuthenticationFailedException("Invalid token. Cause:"+e.getMessage()); } } else { filterChain.doFilter(request, response); } } } </code></pre> <p>Method that creates the Authentication token:</p> <pre><code>String token = Jwts.builder().setSubject(user.getEmail()) .claim("role", user.getRole().name()).setIssuedAt(new Date()) .signWith(SignatureAlgorithm.HS256, JWTTokenAuthFilter.JWT_KEY).compact(); authResp.put("token", token); authResp.put("user", user); </code></pre> <p>Above i have all the claims that i am using on the JWT , i would like to request that the token is revoked after x ammount of time(of inactivity if possible).</p> <p>How could i achieve this using JWT / Spring MVC / Angular JS / Spring Security</p>
22,692,739
0
<p>I'm not aware of any python modules that implement NTLM.</p> <p>But I think this type of authenticated transaction is much more involved than what you're focusing on here. The link you referenced actually contains much more details if you change your starting point from <code>AV_PAIRS</code> structure to the <code>Introduction</code> instead: <a href="http://msdn.microsoft.com/en-us/library/cc236622.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/cc236622.aspx</a></p> <p>That said, in order to tackle this correctly, you must first learn about the <code>struct</code> module, because you'll need to use it to create the NTLM message headers. At the same time, also learn about bit shifting and network-byte-order/host-byte-order, because you're going to need that as well.</p> <p>A simple protocol to practice on would be ICMP. Learn how to read and write that header first, using <code>struct</code> and the others I mentioned. When you're more comfortable, then try and tackle creating and reading NTLM messages.</p> <p>Hope this helps.</p>
18,425,955
0
<pre><code>/ is a culture sensitive data seperator character in your format String :`"MM/dd/yyyy"` </code></pre> <p>And the Final argument <code>null</code> means you specified to use Current Culture. Check you current culture. Is it <code>en-US</code> ? OR you can also Use <code>InvariantCulture</code></p> <p>use this:</p> <pre><code>DateTime dt =DateTime.ParseExact("19/10/2009", "MM/dd/yyyy", new CultureInfo("en-US")); </code></pre> <p>OR Use InvariantCulture</p> <pre><code>DateTime dt = DateTime.ParseExact("19/11/2011", "MM/dd/yyyy", CultureInfo.InvariantCulture); </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/w2sa9yss%28VS.80%29.aspx" rel="nofollow">Read MSDN</a> for complete details.</p>
10,887,980
1
libjpeg.so.62: cannot open shared object file: No such file or directory <p>I am trying to do some image processing with python and the PIL. I was having a problem that I wouldn't correctly import the _imaging folder so I did a reinstall and now I am getting this problem:</p> <pre><code>libjpeg.so.62: cannot open shared object file: No such file or directory </code></pre> <p>I did apt-get remove python-imaging in the command line and then apt-get install python-imaging and now it won't work in Eclipse. Any tips?</p>
37,558,456
0
R change character encoding of a character vector <p>I read in two data frames from two different excel spreadsheets using openxlsx::read.xlsx. I want to get the common column names. With</p> <pre><code>intersect(colnames(nutrients), colnames(req.EAR)) </code></pre> <p>the output is </p> <pre><code>[1] "carbohydrate_g" "calcium_mg" "iron_mg" "magnesium_mg" "phosphorus_mg" "zinc_mg" "vit_c_mg" [8] "thiamin_mg" "riboflavin_mg" "niacin_mg" "vit_b6_mg" "folate_µg" "vit_b12_µg" "vit_a_rae_µg" [15] "vit_e_mg" </code></pre> <p>a common element - vit_d_μg - doesn't show up in the intersection. I suspected this was because in both spreadsheets, element that contain μ are coded as UTF-8 while the rest are "unknown".</p> <p>The cause of all of this I think is the mu (μ) in the column name. I originally thought this was due to the fact that element names with mu in it were encoded as UTF-8 while the others were "unknown".</p> <p>The real reason is that there are two UTF-8 characters that look like mu. At this website ([<a href="http://www.fileformat.info/info/charset/UTF-8/list.htm]" rel="nofollow">http://www.fileformat.info/info/charset/UTF-8/list.htm]</a></p> <pre><code>GREEK SMALL LETTER MU (U+03BC) looks like μ. MICRO SIGN (U+00B5) looks like µ. </code></pre> <p>Someone (probably me) made a mistake in adding the mu to the spreadsheet.</p>
22,781,614
0
<p>A better solution would be to use the django template system. Have the user enter the message in django template format like: Dear {{contactname}}, This is your booking confirmation for your vacation from {{startdate}} to {{enddate}} for a total of {{numdays}} days. Please click {{cancellink}} to cancel your booking.</p> <p>And then use <code>get_template_from_string</code> from <code>django.template.loader</code> and get a template instance. Than you can render the template by doing template.render(context), Where context is a <code>Context</code> instance found in <code>django.template.context</code>. You can read more about django template api in <a href="https://docs.djangoproject.com/en/1.6/ref/templates/api/" rel="nofollow">https://docs.djangoproject.com/en/1.6/ref/templates/api/</a> Should be simple from here.</p>
9,356,336
0
<p>The function you have, despite being called <code>ButtonConstructor</code>, is not a constructor.</p> <p>In Java, a constructor must share the name of its parent class (and have no return type). The correct signature would be <code>public TicTacToePanel()</code>.</p> <p>I cannot say for sure without seeing a more complete view of your code (you have surely omitted most of it), but it is likely that you are not calling the function with which you provided us at all, but rather using the implied no-argument constructor. Try renaming the function to the signature I gave above.</p>
11,148,260
0
<p>The second parameter in <a href="https://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx" rel="nofollow"><code>Substring</code></a> is the length of the substring, not the end index.</p> <p>You should probably include handling to check that it does indeed start with what you expect, end with what you expect, and is at least as long as you expect. And then if it doesn't match, you can either do something else or throw a meaningful error.</p> <p>Here's some example code that validates that url contains your strings, that also is refactored a bit to make it easier to change the prefix/suffix to strip:</p> <pre><code>var prefix = "www.example.com/"; var suffix = ".jpg"; string url = "www.example.com/aaa/bbb.jpg"; if (url.StartsWith(prefix) &amp;&amp; url.EndsWith(suffix) &amp;&amp; url.Length &gt;= (prefix.Length + suffix.Length)) { string newString = url.Substring(prefix.Length, url.Length - prefix.Length - suffix.Length); Console.WriteLine(newString); } else //handle invalid state </code></pre>
15,919,755
0
<p>try using this </p> <pre><code>&lt;TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="bottom" android:stretchColumns="*"&gt; &lt;TableRow android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center_horizontal"&gt; &lt;Button android:id="@+id/btnManualLookup" android:text="ABC" android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight="1" android:textColor="#000000" android:padding="20dip" android:gravity="center"/&gt; &lt;Button android:id="@+id/downloadcerti" android:text="DEF" android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight="1" android:textColor="#000000" android:padding="20dip" android:gravity="center"/&gt; &lt;Button android:id="@+id/settingsbutton" android:text="GHI" android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight="1" android:textColor="#000000" android:padding="20dip" android:gravity="center"/&gt; &lt;/TableRow&gt; </code></pre>
13,545,229
0
How to get raw mouse events in Excel <p>I have an Excel workbook app that includes a low-level definition of a chart. It's not an Excel built-in but one I defined following the [WorkBook->Sheets->WorkSheet->ChartObjects->ChartObject->Chart->[Chartarea, Shapes]] chain. I don't want to talk about how long it took to break <strong>that</strong> cipher.</p> <p>All the drawing stuff works and I'm able to draw lines and place text on the chart.</p> <p>Now I want to capture mouse events and if they're inside the chart limits, act on them. I've tried everything I can think of including right clicking on the chart and doing the "Assign Macro" bit. The sub is never triggered.</p> <p>There has to be a place to put a blahblah_onMouseDown(), but I can't find it.</p> <p><a href="http://smpro.ca/sipmath/SIPshaper1.xlsm" rel="nofollow">The current state of the workbook is here</a></p> <p>Any help would be very much appreciated.</p>
23,896,780
0
<p>XSLT doesn't operate on a sequence of characters, but on the tree defined by the XPath data model. There are some properties of the input that the XSLT processor cannot preserve, because it does not see them in the first place. This includes the amount of whitespace between attribute-value specifications in start-tags, the difference between literal characters and numeric character references, and the line-boundary sequences (CRLF, LF, or CR) in the input.</p> <p>If the reason you want to change as little as possible is that you have downstream processes which only kind of, sort of, understand XML, then some XML users will tell you that what you should do is get rid of that broken software and use XML-aware software instead.</p> <p>If the reason you want to change it as little as possible is that it's beautifully formatted and you don't want it mucked up, you may be able to reproduce your beautiful formatting with XSLT. Or not.</p> <p>If you really really need to preserve the distinction between Unix LF sequences and Windows CRLF sequences, you may want to consider some tool that takes a lower-level view of things. Perhaps you can write your transformation in sed. Perhaps you can write a simple transformation in sed that will turn the data into a form that you can read, modify, and rewrite with XSLT without information loss (and then another sed transform to read the XSLT output and put it back into the Win/Unix mix format). Some people would prefer to use Perl instead of sed. Some would do it all in Elisp.</p>
27,592,454
0
<p>This regex matches valid URLs according to your rules:</p> <pre><code>http((\:\/\/greenbook\.americansalon\.com\/(((leaf|cat)\/(Haircolor|Cosmetics|Shampoos))|company\b).*)|(s?\:\/\/(?!greenbook\.americansalon\.com).*)) </code></pre> <p><a href="https://regex101.com/r/mE0gG2/1" rel="nofollow"><strong>Online demo</strong></a></p>
15,531,922
0
<p><code>package</code> is a <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html" rel="nofollow">reserved word</a>, don't use it as part of a package name. If you try to add a package with "package" as part of it in Eclipse, you will get an error message:</p> <pre><code>Invalid package name. 'package' is not a valid Java identifier </code></pre> <p>Rename the package, then remove the import statement. You don't need to import a file that's in the same package as the one it's referenced in.</p>
41,018,986
0
<p>I have finally made the connection to my database by creating a WorkItemHandler and add it as a dependency to my BPM Suite project. After a lot of search, i think this is the best way to do it if anyone wants to access his database in a business process.</p>
9,838,752
0
<p>It actually looks fine to me. Try refreshing your CSS by clearing your browser cache.</p> <p><img src="https://i.imgur.com/k2E9P.png" alt="image"></p>
39,814,142
0
No resource identifier found for attribute 'srcCompat' in package '....' <p>I will being by saying that I have seen SOME answers for this question on stackoverflow already, but only providing a quick 'fix' solution. I would like, if possible, to also understand WHY this is happening (an answer with some detailing).</p> <p>Now to get to the question: I have just re-started android development, using Android Studio 2.2 . I have an ios app which I want to port to android (meaning, recreate it for Android). I have started with a basic template from Android Studio, added a Constraint Layout and 2 ImageViews using 2 PNG files that I have copied in DRAWABLE folder.</p> <p>Without making any changes or whatsoever , when I try to build I get this error:</p> <p>Error:(11) No resource identifier found for attribute 'srcCompat' in package 'x.y.z'. This happens for both images. Here is the layout file:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/lib/x.y.z" xmlns:app2="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="x.y.z.MainActivity"&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" app2:srcCompat="@drawable/pngFile1" android:id="@+id/imageView" app2:layout_constraintBottom_toBottomOf="parent" android:layout_marginEnd="8dp" app2:layout_constraintRight_toRightOf="parent" android:layout_marginBottom="8dp" android:layout_marginRight="8dp" /&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" app2:srcCompat="@drawable/pngFile2" android:id="@+id/imageView2" app2:layout_constraintBottom_toTopOf="@+id/imageView" app2:layout_constraintRight_toRightOf="@+id/imageView" android:layout_marginBottom="8dp" /&gt; </code></pre> <p></p> <p>Now, here are some things that I would like to understand, in order to have a proper answer to my question:</p> <ul> <li><p>some of the other answers I have found on SO propose to change the default:</p> <p>xmlns:app="http://schemas.android.com/apk/res-auto"</p></li> </ul> <p>to:</p> <pre><code>xmlns:app="http://schemas.android.com/apk/lib/x.y.z" </code></pre> <p>It's true that this removes the error from the build, but what seems strange to me (with my little-to-none android experience), is that Android Studio creates then another similar line when i add the 2nd image:</p> <pre><code>xmlns:app2="http://schemas.android.com/apk/res-auto" </code></pre> <p>And as we can see, it uses this for the images, so the errors appear again. </p> <p>I remember like one year ago i had worked on an app on Android Studio, and have used almost the same way of adding images / buttons with images and these problems were not there.</p> <p>That's why I would also like to understand why this is happening and how to fix it properly.</p> <p>Thanks in advance !</p>
24,635,456
0
<p>Dividing with a float 100. value should covert it into a float. After that, it's only a matter of formatting to display it the way you like.</p> <pre><code>$ python Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; number = 99990 &gt;&gt;&gt; print("{0:.2f}".format(number / 100.)) 999.90 </code></pre>
1,808,498
0
<p>Basically if a user gets any error other than 403 or 404 (most notable other than those is 500 which is sent if there's an exception) they'll be redirected to that page, which won't exist (And if you're in IIS7 integrated pipeline or have IIS6 wildcard mapped they'll then get bounced to FileNotFound.htm - otherwise they'll just see a standard 404).</p> <p>It'd probably be nice to at least give the user a "Oh no! Something is wrong!" page.</p>
18,327,890
0
<p>ok, looks like sqlite either doesn't have what I need, or I am missing it. Here's what I came up with:</p> <ul> <li><p>declare zorder as integer primary key autoincrement, zuid integer in orders table</p> <p>this means every new row gets an ascending number, starting with 1</p></li> <li><p>generate a random number:</p> <p>rnd = int(random.random() * 1000000) # unseeded python uses system time</p></li> <li><p>create new order (just the SQL for simplicity):</p> <p>'INSERT INTO orders (zuid) VALUES ('+str(rnd)+')'</p></li> <li><p>find that exact order number using the random number:</p> <p>'SELECT zorder FROM orders WHERE zuid = '+str(rnd)</p></li> <li><p>pack away that number as the new order number (newordernum)</p></li> <li><p>clobber the random number to reduce collision risks</p> <p>'UPDATE orders SET zuid = 0 WHERE zorder = '+str(newordernum)</p></li> </ul> <p>...and now I have a unique new order, I know what the correct order number is, the risk of a read collision is reduced to negligible, and I can prepare that order without concern that I'm trampling on another newly created order.</p> <p>Just goes to show you why DB authors implement sequences, lol.</p>
19,245,842
0
<p><code>std::endl</code> calls <code>flush</code> stream while <code>cout &lt;&lt; "\n"</code> does not flush the stream, so <code>cout &lt;&lt; "\n";</code> gain better performance, especially while you call it in loop.</p> <p>§27.7.3.8 <strong>Standard basic_ostream manipulators</strong></p> <pre><code>namespace std { template &lt;class charT, class traits&gt; basic_ostream&lt;charT,traits&gt;&amp; endl(basic_ostream&lt;charT,traits&gt;&amp; os); } 1 Effects: Calls os.put(os.widen(’\n’)), then os.flush(). </code></pre>
37,791,594
0
<p>In order to make TDS work in your local solution, you need to right click the TDS project, select Properties and make sure you have the "Install Sitecore Connector" checked under the Build tab. Click on TEST and let the process run.</p> <p>If you have multiple TDS projects in the same solution, make sure you have the same GUID defined on each project.</p> <p><a href="https://i.stack.imgur.com/xnkS9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xnkS9.png" alt="enter image description here"></a></p>
21,444,961
0
Not being able to create a push notifier in apigee <p>I am trying to create a push notifier for my app. I follow the instructions provided: upload a .p12, name the notifier, development, etc. and then click create notifier. However the button does nothing! Anyone else facing the same issue?</p>
38,094,981
0
Linux checking shell command (bash) <p>How can I check if a shell command ends with some text? For instance if I type </p> <pre><code>$ http://example.com/file.webm </code></pre> <p>(ends with .webm) it will be automatically replaced with </p> <pre><code>$ wget http://example.com/file.webm </code></pre> <p>Of course only if command consists of one part.</p> <p>I'm using <code>bash</code> as my shell.</p>
36,409,578
0
<p>Any view can implement both "get" and "post" handling; that way you can have something like </p> <pre><code>class BookCreateView(views.View): # subclass the basic form and add an hidden input named search form = your_custom_search_form # subclass the create model form confirmation_form = your_custom_create_model_form def get(request): # show the empty search page # in your template use the form to implement search def post(request): # handle the book search; there is a data in the payload named search # you now have a payload to use; here you make a database query # and return the similar books; every book is printed in the page # using the your_custom_create_model_form that you can prepopulate # handle the confirmation of the book otherwise; the post # payload will contain the book information </code></pre>
38,789,837
0
<p>Your application import_name can't be identified properly in *.tac file. If you create flask application in *.py file and import it in *.tac it will work just fine.</p> <p>But you also need another list of <a href="http://twistedmatrix.com/documents/current/web/howto/web-in-60/wsgi.html" rel="nofollow">instructions</a> for deploying Flask application via twistd. Minimal example looks like this:</p> <pre><code>from twisted.application import internet, service from twisted.web.server import Site from twisted.web.wsgi import WSGIResource from twisted.internet import reactor from my_flask_module import my_flask_app application = service.Application('myapplication') service = service.IServiceCollection(application) flask_resource = WSGIResource(reactor, reactor.getThreadPool(), my_flask_app) flask_site = Site(flask_resource) internet.TCPServer(8000, flask_site).setServiceParent(service) </code></pre>
30,620,923
0
<p>If you want to display a table with all the possible properties in the header, and each row with each column filled or not whether the property is defined or not for the document in that row, then you will need to:</p> <ol> <li>Ahead of time (in <code>onCreated</code> or <code>onRendered</code>), find <em>all</em> possible properties for your dataset, order them, and store them in a "header" object accessible to your helpers. (either in <code>Session</code> or using a <a href="http://docs.meteor.com/#/full/reactivevar_pkg" rel="nofollow">reactive variable</a>) Make it reactive if necessary, using <code>this.autorun()</code>.</li> <li>Then, do the same as above, except just returning the stored ordered list for <code>tableHeader</code></li> <li>And for <code>rowContent</code>, iterate over your stored header and fill an array with empty strings for each undefined field in the current document</li> </ol> <p>Example:</p> <pre><code>function getHeader(products) { var header = {}; for (var key in products) { for (var property in products[key]) { header[property] = true; } } return Object.keys(header); } Template.productvalue.onRendered(function () { var products = Products.find().fetch(); Session.set('header', getHeader(products)); this.autorun(function () { var products = Products.find().fetch(); Session.set('header', getHeader(products)); }); }); Template.productvalue.helpers({ 'tableHeader': function () { return Session.get('header'); }, 'rowContent': function (document) { var row = []; var header = Session.get('header'); for (var key in header) { row.push(document[header[key]] || ""); } return row; } }); </code></pre> <p>And in template:</p> <pre><code>&lt;template name="productvalue"&gt; &lt;table&gt; &lt;thead&gt; {{#each tableHeader}} &lt;th&gt;{{this}}&lt;/th&gt; {{/each}} &lt;/thead&gt; &lt;tbody&gt; {{#each products}} &lt;tr&gt; {{#each rowContent this}} &lt;td&gt;{{this}}&lt;/td&gt; {{/each}} &lt;/tr&gt; {{/each}} &lt;/tbody&gt; &lt;/table&gt; &lt;/template&gt; </code></pre> <p>I still recommend <a href="https://dweldon.silvrback.com/scoped-reactivity" rel="nofollow">using a reactive variable</a> instead of <code>Session</code>, but the demonstration is complicated enough as it is.</p>
36,375,946
0
<ol start="3"> <li>As an alternate solution you may simply not use HTML helpers and write your own HTML. Using HTML helpers leads to issues such as those you are encountering. You may overcome them, but what is the point using HTML helpers if instead of helping you, they create difficulties? (In my point of view, MVC is about having control over the front code you serve to browsers.)</li> </ol> <p>With Razor, writing directly the required HTML can prove more effective than letting HTML helpers do that for you.</p> <p>Granted, this is my point of view. I have detailed it a bit more on some similar question <a href="/a/36084744/1178314">here</a>.</p>
8,612,479
0
<p><code>n/10</code> will not shift the decimal number since <code>n</code> is an integer. The division will produce the result like this: if n = 25, then <code>n/10</code> would be 2 (without any decimal points), similarly if n = 9, then n/10 would be 0 in which case <code>if</code> condition would not be satisfied.</p> <p>Regarding the <code>+'0'</code>, since n%10 produces an integer result and in <code>putchar</code> you are printing a <code>char</code> , you need to convert the integer to a char. This is done by adding the ascii value of 0 to the integer.</p>
4,828,384
0
<p>Check the process id parents - you probably will see one parent and 2 children.</p> <p>Historically - MANY entries appeared in the ps table per <a href="http://wiki.apache.org/tomcat/FAQ/Linux_Unix" rel="nofollow">http://wiki.apache.org/tomcat/FAQ/Linux_Unix</a></p> <p>In new linux kernels - ps/top have whittled these down to one. But jsvc launches in a parent/child style which would explain 2 processes (but not 3). </p> <p>But long story short - it is probably nothing to worry about.</p>
10,866,146
0
<p>I'll throw an alternative solution into the mix. It is, unapologetically, a huge ugly hack, but gets around a problem.</p> <p>If you have an array called 'theArray' like this</p> <pre><code>100 =&gt; 'a' 200 =&gt; 'b' 300 =&gt; 'c' </code></pre> <p>then replacing</p> <pre><code>for (key in theArray) </code></pre> <p>with </p> <pre><code>for (var i=0; i &lt; theArray.length; i++) </code></pre> <p>does not really help, because the length is '3', but you have keys much higher than the array length. Presumably the keys in such instances have significance, and you want to keep them.</p> <p>The hackish way to fix it is to force JavaScript to treat the keys as strings, not integers. You can do this by doing something quick and dirty like renaming all your keys to</p> <pre><code>"a100" =&gt; 'a' "a200" =&gt; 'b' "a300" =&gt; 'c' </code></pre> <p>Then use some sort of substring function when you want to use the key value later on in your code.</p> <p>Once the keys are treated as strings, all browsers I am aware of will display them in the order they were created, not in any other order.</p> <p>I should add a disclaimer - it's probably better to write your code to avoid this scenario in the first place by not using keys as a means to carry information in this way.</p> <p>eg:</p> <pre><code>0 =&gt; array (100,'a') 1 =&gt; array (200,'b') </code></pre> <p>etc</p> <p>This hack is something I've employed as a quick fix where I didn't want to rewrite a lot of code to not use 'meaningful' integers as keys.</p>
23,736,801
0
Delete link behaviour lost when I regenerate HTML. How can I handle this? <p>If I regenerate a Rails delete link on my page, something like the following:</p> <pre><code>&lt;a href="/categories/19" data-method="delete" data-confirm="Are you sure?" ..&gt;Link&lt;/a&gt; </code></pre> <p>When this page loads, something in Rails must set the behaviour of this link as I get a nice "Are you sure?" before I commit to delete something. However, when I regenerate the HTML I'm guessing I need to re-initialize the behaviour but I'm not sure where this comes from. Can anyone tell me if there is a function I should call again after I generate this HTML link? Thanks</p>
33,252,144
0
when to use Repository methods and when to use mongoTemplate? <p>I am working on <code>Spring data mongo</code> with my <code>Spring MVC</code> application. I need to understand which is the correct way to improve performance if I wish to use multiple criteria's.</p> <ul> <li>Do I need to go for <code>Repository</code> methods? Or</li> <li>Do I need to go for <code>MongoTemplate</code>/<code>MongoOperations</code>?</li> </ul> <p>Which is advisable to use to improve performance with many contional criteria's ?</p>
28,759,544
0
Google Spreadsheet xpath scraping <p>So I'm not a professional programmer, but I'm trying to scrape data off the Reuters homepage and import it into google spreadsheets. I know that there have already been questions answerd about scraping from Reuters, however, that didn't help me.</p> <p>I want data from this page: <a href="http://www.reuters.com/finance/stocks/financialHighlights?symbol=9983.T" rel="nofollow">http://www.reuters.com/finance/stocks/financialHighlights?symbol=9983.T</a></p> <p>specifically, if you scroll down, there's a lot of data on the company's financials, packed into tables. I need specific values out of the tables.</p> <p>So naturally my question to you is, how can I get specific values out of the tables? For instance, I want the first value out of the line that's labelled "Net Profit Margin (TTM)". The value should be 7.30.</p> <p>So I got the xpath by using google chrome developer tools, right-click on the element and select "copy xpath". Since I'm not a programmer I dont know any other way for arriving at a specific element from the tables.</p> <p>I tried the following function in google spreadsheets:</p> <pre><code>=IMPORTXML(URL as written above,"//*[@id='content']/div[2]/div/div[2]/div[1]/div[13]/div[2]/table/tbody/tr[14]/td[2]") </code></pre> <p>but it returns</p> <pre><code>"#N/A - Error, imported content is empty" </code></pre> <p>What can I do to get the value?</p>
20,501,416
0
<p>LINQ statements return IEnumerable objects, and your method is returning a single Request object. In your case looks like you only need to return the first result of the LINQ statement.</p> <p>Something like:</p> <pre><code> Dim pr = (From r In dc.Request From p In dc.Process.Where(Function(v) v.IdReq = r.IdReq And v.idProcess Is Nothing) Select New {Request = r}).FirstOfDefault Return pr </code></pre>
19,243,938
0
Keep the text in textboxes saved <p>I have these textboxes where the user enters data and then presses a button to process the data. Now the data entered by the user is alot and to give the user some slack I want to make it possible whenever you press the button, the application saves the data, so when you close the application and start it back up again the textboxes are filled with the last entered data.</p> <p>I was thinking about using a .txt file to save the data. Only I have found some difficulties with this. One of the problems is that I keep getting a messagebox from the microsoft .NET Framework everytime I try to run my application. The messagebox says the Index was outside the bounds of the array. Even though I think my code doesn't exceed the bounds of my array.</p> <p>And here is the code that I use:</p> <p>First I declared an array and filled it with variables that contain the content of the textboxes:</p> <pre><code>string[]settings = new string[5]; settings[0] = openKey; settings[1] = secretKey; settings[2] = statusRequestPath; settings[3] = statusRequestAPI; settings[4] = setSeconds.ToString(); </code></pre> <p>Then I use the following code to write the data to a text file.</p> <pre><code>using (StreamWriter writeFile = new StreamWriter(@"C:\Audio Silence Detector\AudioSilenceDetector.txt")) { foreach (string line in settings) { writeFile.WriteLine(line); } } </code></pre> <p>And to put the text of the .txt file back in the application I have put this in the formload:</p> <pre><code>string[] lines = System.IO.File.ReadAllLines(@"C:\Audio Silence Detector\AudioSilenceDetector.txt"); tbOpenKey.Text = lines[0]; tbSecretKey.Text = lines[1]; tbStatusRequestPath.Text = lines[2]; tbStatusRequestAPI.Text = lines[3]; tbSeconds.Text = lines[4]; </code></pre> <p>I changed my code to this and it seems to have fixed the issue I was having:</p> <pre><code> if (lines.LongLength == 5) { tbOpenKey.Text = lines[0]; tbSecretKey.Text = lines[1]; tbStatusRequestPath.Text = lines[2]; tbStatusRequestAPI.Text = lines[3]; tbSeconds.Text = lines[4]; } </code></pre>
2,168,111
0
<p>There is a nice overview on <a href="http://en.wikipedia.org/wiki/Design_by_contract" rel="nofollow noreferrer">WikiPedia about Design by Contract</a>, at the end there is a section regarding <a href="http://en.wikipedia.org/wiki/Design_by_contract#Languages_with_third-party_support" rel="nofollow noreferrer">languages with third party support libraries</a>, which includes a nice serie of Java libraries. Most of these Java libraries are based on Java Assertions. </p> <p>In the case you only need <a href="http://en.wikipedia.org/wiki/Precondition" rel="nofollow noreferrer">Precondition Checking</a> there is also a lightweight <a href="http://www.javapractices.com/topic/TopicAction.do?Id=5" rel="nofollow noreferrer">Validate Method Arguments</a> solution, at SourceForge under <a href="http://java-arg-val.sourceforge.net/introduction.html" rel="nofollow noreferrer">Java Argument Validation</a> (Plain Java implementation).</p> <p>Depending on your problem, maybe the <a href="http://oval.sourceforge.net/" rel="nofollow noreferrer">OVal</a> framework, for field/property Constraints validation is a good choice. This framework lets you place the Constraints in all kind of different forms (Annotations, POJO, XML). Create customer constraints through POJO or scripting languages (JavaScript, Groovy, BeanShell, OGNL, MVEL). And it also party implements <a href="http://en.wikipedia.org/wiki/Design_by_contract" rel="nofollow noreferrer">Programming by Contract</a>.</p>
36,455,337
0
<p>Finally, I managed to make it work... so thank you to those who gave me comments:</p> <pre><code>df1$diff_order &lt;- reorder(df1$country.name, df1$diff) #Set order of countries by diff, and then set this to be plot a &lt;- ggplot(df1, aes((x=diff_order), y=diff,fill=as.factor(level))) + geom_bar(stat="identity") + xlab("Country") + theme_classic() + coord_flip() + scale_fill_manual(values=c("#009E73", "#0072B2"),name="NUTS level") + ggtitle("All") + theme(plot.title = element_text(hjust = 0)) + theme(axis.title.x = element_blank()) + theme(axis.text=element_text(size=9), axis.title=element_text(size=10,face="bold")) a </code></pre> <p><a href="https://i.stack.imgur.com/oUrQQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oUrQQ.png" alt="enter image description here"></a></p>
39,635,318
0
Can't get autocomplete of some bootstrap style classes in WebStorm <p>WebStorm version: <strong>2016.2.3</strong></p> <p>Bootstrap version: <strong>3.3.7</strong></p> <p>Way of including bootstrap files: <strong>Locally</strong></p> <p>Issues: Can't get autocomplete of some style classes. For example:</p> <p><img src="https://i.stack.imgur.com/PQkBL.png" alt="&quot;no &lt;code&gt;table-hover&lt;/code&gt;&quot;"></p>
33,875,238
1
Export Pandas data frame with text column containg utf-8 text and URLs to Excel <p>My Pandas data frame consists of Tweets and meta data of each tweet (300.000 rows). Some of my colleagues need to work with this data in Excel which is why I need to export it.</p> <p>I wanted to use either <code>.to_csv</code> or <code>.to_excel</code> which are both provided by Pandas but I can't get it to work properly.</p> <p>When I use <code>.to_csv</code> my problem is that it keeps failing in the text part of the data frame. I've played around with different separators but the file is never 100% aligned. The text column seems to contain tabs, pipe characters etc. which confuses Excel.</p> <pre><code>df.to_csv('test.csv', sep='\t', encoding='utf-8') </code></pre> <p>When I try to use <code>.to_excel</code> together with the <code>xlsxwriter</code> engine I'm confronted with a different problem, which is that my text column contains to many URLs (I think). <code>xlswriter</code> tries to make special clickable links of these URLs instead of just handling them as strings. I've found some information on how to circumvent this but, again, I can't get it to work.</p> <p>The following bit of code should be used to disable the function that I think is causing trouble:</p> <pre><code>workbook = xlsxwriter.Workbook(filename, {'strings_to_urls': False}) </code></pre> <p>However, when using <code>to_excel</code> I can't seem to adjust this setting of the Workbook object before I load the data frame into the Excel file.</p> <p>In short how do I export a column with wildly varying text from a Pandas data frame to something that Excel understands?</p> <p><strong>edit:</strong> example:</p> <pre><code>@geertwilderspvv @telegraaf ach Wilders toch, nep-voorzitter van een nep-partij met maar één lid, \nzeur niet over nep-premier of parlement! </code></pre> <p>So in this case It is obviously a line brake that is my data. I will try to find some more examples.</p> <p><strong>edit2:</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"&gt;&lt;logFileName&gt;error047600_01.xml&lt;/logFileName&gt;&lt;summary&gt;Er zijn fouten aangetroffen in bestand C:\Users\Guy Mahieu\Desktop\Vu ipython notebook\pandas_simple.xlsx&lt;/summary&gt;&lt;removedRecords summary="Hier volgt een lijst van verwijderde records:"&gt;&lt;removedRecord&gt;Verwijderde records: Formule van het onderdeel /xl/worksheets/sheet1.xml&lt;/removedRecord&gt;&lt;/removedRecords&gt;&lt;/recoveryLog&gt; </code></pre> <p>Translation of Dutch stuff:</p> <p>Errors were found in "file". Here follows a list of removed records: removed records: formula of the part /xl/worksheets/sheet1.xml</p>
8,286,847
0
Issue while publishing Android app: "This application is available to over 0 devices" <p>Hello: I note this question has been answered at <a href="http://stackoverflow.com/q/8212956/936042">http://stackoverflow.com/q/8212956/936042</a> but I hope y'all will entertain my question since I am not able to reproduce the solution.</p> <p>When I upload my APK to the Android market, the message says "available to over 578 devices" (this is before activation). As soon as I begin to make other changes (such as changing the contact email address) the message changes to "This application is available to over 0 devices". I use Eclipse's Export option to created the final, signed APK.</p> <p>My Android app uses 3 external JARs (http://code.google.com/p/javamail-android/downloads/list). I add them to the project using Project/Properties/Java Build Path/Libraries/Add External JARs.</p> <p>The solution posted at the link above implicates the use of external JARS, and their being embedded into the APK in some inappropriate manner, as the cause for this issue:</p> <blockquote> <p>my mistake was that I included .jar files in order to add some external libraries and not the respective external class folders. When I removed the .jar files and I just added the class folder then devices became over 700 again.</p> </blockquote> <p>I don't quite follow the above explanation. If someone (especially the original author) could lay it out in greater detail, I'll be very obliged.</p> <p>Thanks!</p> <p>PVS</p>
36,774,117
0
Using Regex to recognize pattern in string <p><em>I apologize if this is a repeat question, as I know there are many about Regex on StackOverflow, but I have yet to find an answer or a level of help I need.</em></p> <blockquote> <p>I have a string that needs to be a length of 8 where:</p> <ul> <li><p>The first two characters are letters</p></li> <li><p>The next five characters are numbers</p></li> <li><p>The last character is a letter</p></li> </ul> <p>For example: "AB12345C"</p> </blockquote> <p>I have been using the examples from <a href="https://msdn.microsoft.com/en-us/library/sdx2bds0(v=vs.110).aspx" rel="nofollow">MSDN</a> &amp; <a href="http://www.dotnetperls.com/regex" rel="nofollow">DotNetPerls</a> to try and understand how to use arguments properly, but after a couple days of reading around I still can't get it to pass.</p> <p>I am currently trying to use:</p> <pre><code>public Tuple&lt;bool, string&gt; stringFormatCheck(string input) { if (Regex.IsMatch(input, @"^[a-zA-Z]\d{2}[0-9]\d{5}[a-zA-Z]$") == true) return Tuple.Create(true, "String is Fine"); else return Tuple.Create(false, "String Format is incorrect"); } </code></pre> <p>Can someone show me how to use this argument properly or somewhere I can get a better understanding of the Regex Class? Thank you.</p> <p>EDIT1: The second Z in my first argument is now capitalized.</p>
30,674,843
0
Android Instance Variables <p>Are instance variables preferred over local variables or vice versa? For instance, with using <code>SharedPreferences</code>, should it be declared at the top of the class and then referenced throughout or should it just be declared in each method it is needed?</p> <p>I am wondering if there would be a large difference in memory usage since the instance variable would last as long as the activity; however, it would be cleaner since I would not need to instantiate it in every method it is used.</p>
34,392,388
0
<p>Pointers to functions and pointers to member functions are different beasts. While functions decay to pointers to functions, the same is not true for member functions or member objects. While there is a standard function to pointer conversion there is nothing similar for member functions or member objects. When you want to get a pointer to member you always need to use an <code>&amp;</code>.</p> <p>I don't know the exact reasoning but I suspect that the address-of operator was required to avoid mistakes which sometimes show up with functions, e.g.:</p> <pre><code>int f(); // ... if (f) { // always true } </code></pre> <p>While the implicit conversion from functions to function pointers couldn't be removed without breaking C compatibility, there was no similar concern when members and pointer to members were introduced.</p>
5,208,335
0
<p>try simply indicating ctypes the argtypes it takes and the ones it returns:</p> <pre><code>nDll = ctypes.WinDLL('ndll.dll') nDll.restype = ctypes.c_double nDll.argtypes = [ctypes.c_char_p] result = nDll.iptouint("12.345.67.890").value </code></pre> <p>Although, consider these points:</p> <p>1) if, as the name indicates, this converts an IPv4 value s ina string to an Unsigned Int, the return type os not "double" as you say - it would be ctypes.c_uint32 </p> <p>2) Your example value is not a valit IPv4 address, and cannot be converted to a 32 bit integer (neither does it makes sense as a "double" - i.e. a 64 bit floating point number) - it is simply invalid</p> <p>3) You don't need that if you are just trying to have an unsigned 32bit value for an ipv4 address in Python. There are quite a few, very readable, easier, and multiplatform ways to do that with pure python. For example:</p> <pre><code>def iptoint(ip): value = 0 for component in ip.split("."): value &lt;&lt;= 8 #shifts previous value 8 bits to the left, #leaving space for the next byte value |= int(component) # sets the bits for the new byte in the address return value </code></pre> <p><strong>update</strong>: In Python 3.x there is the ipaddress module - <a href="https://docs.python.org/3/library/ipaddress.html" rel="nofollow">https://docs.python.org/3/library/ipaddress.html</a> - which is also available as a pip install for Python 2.x - it can handle this always in the correct way, and works fine with IPv6 as well.</p>
29,911,834
0
Program(java) skips nextLine() prompt and continues with program <p>here is the code:</p> <pre><code>import java.util.Scanner; public class DriverProject1 { public static void main(String[] args) { int roomNumber; int numberOfRooms; int optionNumber; String guestName = null; String phoneNumber; int nightsStaying; double nightlyRate; Scanner keyboard = new Scanner(System.in); System.out.println("How many rooms are in the hotel?"); numberOfRooms = keyboard.nextInt(); Hotel Carnegie = new Hotel(numberOfRooms); do { System.out.println("Welcome to the MENU!"); System.out.println("Please enter a number corresponding to the option desired."); // main menu screen System.out.println("OPTION 1: Put guest into room"); System.out.println("OPTION 2: Remove guest from room"); System.out.println("OPTION 3: Get guest info"); System.out.println("OPTION 4: Get guest count"); System.out.println("OPTION 5: Display guest book"); System.out.println("OPTION 6: Calculate expected income"); System.out.println("OPTION 7: Quit"); optionNumber = keyboard.nextInt(); // choosing an option if (optionNumber == 1) // if option 1 is chosen { System.out.println("What is the guests first name?"); guestName = keyboard.nextLine(); System.out.println("What is the guests Phone number?"); phoneNumber = keyboard.nextLine(); Guest newGuest = new Guest(guestName); newGuest.setPhoneNumber(phoneNumber); </code></pre> <p>"What is the guests first name? What is the guests Phone number?" appears and it will not take anything for the guest name. <code>guestName</code> has been initialized to "". lines 36 -39. not sure of the issue going on. i am using a few methods contained within my hotel class, however i am almost certain they do not contain the error which causes this bug. also the do loop is completed later on in the code. </p>
10,595,101
0
Rails Daily/Monthly Report <p>Report</p> <p>I need to create a daily report + monthly report with this records.. All records is from one table and under one field('nature' is the name of my field)..</p> <pre><code>Calls Texts Emails </code></pre> <p>Is there any possible way to create a single query that will generate this daily report + monthly report.?</p> <p>Ex.</p> <pre><code> Day1 Day2 Day3 etc.. Total Calls 20 23 23 ... 66 Texts 120 125 130 ... 375 Emails 50 60 55 ... 165 Total 190 208 208 ... 606 </code></pre> <p>If not, please tell how to do it the simplest way, and how to this on rails.?</p> <p>Thanks in advance...</p>
9,145,836
0
understanding executing c code in stack ( Mac Hackers Handbook code) <p>I was looking at this example w.r.t executing code in the stack:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; char shellcode[] = “\xeb\xfe”; int main(int argc, char *argv[]){ void (*f)(); char x[4]; memcpy(x, shellcode, sizeof(shellcode)); f = (void (*)()) x; f(); } </code></pre> <p>This causes a segmentation fault. My understanding this is because the shellcode runs out of memory for the rest of the bytes as x only has a size of 4 bytes. And this results in creating a write operation of copying to stack memory and that causes a seg. fault as stack memory is read only. Is my understanding correct ?</p>
13,289,321
0
<p>try to do it,like below code...</p> <p>private void Form1_Load(object sender, EventArgs e) { FillCountry();</p> <pre><code> } private void FillCountry() { string str = "SELECT CountryID, CountryName FROM Country"; SqlCommand cmd = new SqlCommand(str,con); //cmd.Connection = con; //cmd.CommandType = CommandType.Text; // cmd.CommandText = "SELECT CountryID, CountryName FROM Country"; DataSet objDs = new DataSet(); SqlDataAdapter dAdapter = new SqlDataAdapter(); dAdapter.SelectCommand = cmd; con.Open(); dAdapter.Fill(objDs); con.Close(); comboBox1.ValueMember = "CountryID"; comboBox1.DisplayMember = "CountryName"; comboBox1.DataSource = objDs.Tables[0]; } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { if (comboBox1.SelectedValue.ToString() != "") { int CountryID = Convert.ToInt32(comboBox1.SelectedValue.ToString()); FillStates(CountryID); comboBox3.SelectedIndex = 0; } } private void FillStates(int countryID) { string str = "SELECT StateID, StateName FROM State WHERE CountryID =@CountryID"; SqlCommand cmd = new SqlCommand(str, con); // SqlConnection con = new SqlConnection(Con); // cmd.Connection = con; // string str="SELECT StateID, StateName FROM State WHERE CountryID =@CountryID"; // cmd.Connection = con; //cmd.CommandType = CommandType.Text; // cmd.CommandText = "SELECT StateID, StateName FROM State WHERE CountryID =@CountryID"; cmd.Parameters.AddWithValue("@CountryID", countryID); DataSet objDs = new DataSet(); SqlDataAdapter dAdapter = new SqlDataAdapter(); dAdapter.SelectCommand = cmd; con.Open(); dAdapter.Fill(objDs); con.Close(); if (objDs.Tables[0].Rows.Count &gt; 0) { comboBox2.ValueMember = "StateID"; comboBox2.DisplayMember = "StateName"; comboBox2.DataSource = objDs.Tables[0]; } } private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { int StateID = Convert.ToInt32(comboBox2.SelectedValue.ToString()); FillCities(StateID); } private void FillCities(int stateID) { //SqlConnection con = new SqlConnection(str,con); string str = "SELECT CityID, CityName FROM City WHERE StateID =@StateID"; SqlCommand cmd = new SqlCommand(str,con); // cmd.Connection = con; //cmd.CommandType = CommandType.Text; // cmd.CommandText = "SELECT CityID, CityName FROM City WHERE StateID =@StateID"; cmd.Parameters.AddWithValue("@StateID", stateID); DataSet objDs = new DataSet(); SqlDataAdapter dAdapter = new SqlDataAdapter(); dAdapter.SelectCommand = cmd; con.Open(); dAdapter.Fill(objDs); con.Close(); if (objDs.Tables[0].Rows.Count &gt; 0) { comboBox3.DataSource = objDs.Tables[0]; comboBox3.DisplayMember = "CityName"; comboBox3.ValueMember = "CItyID"; } </code></pre>
21,305,875
0
<p>In my opinion the simplest solution:</p> <pre><code>#controllers/application_controller.rb protected def ckeditor_pictures_scope(options = { :assetable_id =&gt; "#{current_page.id}" ,:assetable_type =&gt; "Page" }) ckeditor_filebrowser_scope(options) end def ckeditor_attachment_files_scope(options = { :assetable_id =&gt; "#{current_page.id}" ,:assetable_type =&gt; "Page" }) ckeditor_filebrowser_scope(options) end def ckeditor_before_create_asset(asset) asset.assetable = current_page if current_page return true end </code></pre>
12,558,248
0
<p>Try manually setting your view layers z-property to ensure the hierarchy is what you need.</p>
26,675,462
0
<p><em>Remark, it is a very general question that doesn't fit well to the usage of this community.</em></p> <p>Supervisor are here to control the way your application starts and evolves in time. It starts processes in the right order with a verification that everything is going fine, manage the restart strategy in case of failure, pool of processes, supervision tree... The advantages are that it helps you to follow the "let it crash" rule in your application, and it concentrates in a few line of code the complex task to coordinate all your processes.</p> <p>I use gen_event mainly for logging purposes. You can use this behavior to connect on demand different handlers depending on your target. In one of my application, I have by default a graphical logger that allows to check the behavior at a glance, and a textual file handler that allows deeper and post mortem analysis.</p> <p>Gen_server is the basic brick of all applications. It allows to keep a state, react on call, cast and even simple messages. It manages the code changes and provides features for start and stop. Most of my modules are gen_servers, you can see it as an actor which is responsible to execute a single task.</p> <p>Gen_fsm brings to gen server the notion of a current state with a specific behavior, and transition from state to state. It can be used for example in a game to control the evolution of the game (configuration, waiting for players, play, change level...)</p> <p>When you create an application you will identify the different tasks yo have to do and assign them to either gen_server either gen_fsm. You will add gen_event to allow publish/subscribe mechanism. Then you will have to group all processes considering their dependency and error recovering. This will give you the supervision tree and restart strategy. </p>
10,346,824
0
<p><code>grep</code> uses regexes; <code>.</code> means "any character" in a regex. If you want a literal string, use <code>grep -F</code>, <code>fgrep</code>, or escape the <code>.</code> to <code>\.</code>.</p>
37,232,346
0
<p>Your way is wrong. if you have view for every language, then what's the point to use i18n? </p> <p>You can just get </p> <pre><code>?lang= </code></pre> <p>value and send <code>res.render ( '/' + req.query.lang + '/contact.html').</code></p> <p><em>Try way is</em></p> <pre><code>-locales --en.json --nl.json -view --cabinet.html --main.html </code></pre> <p><strong>app.js</strong></p> <pre><code>i18n.configure({ locales: ['en', 'nl'], directory: __dirname + '/locales', defaultLocale: 'nl', updateFiles: false, objectNotation: true }); app.use(i18n.init); app.use(function (req, res, next) { console.log(i18n); if (req.query.lang != undefined &amp;&amp; i18n.locales.indexOf(req.query.lang) &gt;= 0) { i18n.setLocale(req.query.lang); }else{ i18n.setLocale(i18n.defaultLocale); } next(); }); </code></pre> <p><strong>en.json</strong> example</p> <pre><code>{ "cabinet": { "menu": { "title": "Menu", }, "dashboard": { "title": "Dashboard" }, "statistic": { "datePeriod": "Date period", "choose": "Choose", } }, "main": { "title": "Main", "body": { "hi": "Hi everyone!" } } </code></pre> <p>same for nl.json</p> <p><strong>main.html</strong></p> <pre><code> I use Swig template &lt;html&gt; &lt;head&gt; &lt;title&gt;{{ translate.title }}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; {{ translate.body.hi }}!! &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>router.js</strong></p> <pre><code>router.get('/main', function(req, res, next) { res.render('/main', { title: '...', menu: '...', translate: res.__('main') }); }); router.get('/cabinet', function(req, res, next) { res.render('/cabinet', { title: '...', menu: '...', translate: res.__('cabinet') }); }); </code></pre>
28,808,571
0
Back to page using ajax form with form settings <p>I have a page that offers the user results. From that page there are additional sort options and advanced search options that are submitted by POST by AJAX to a script and the output is inserted into a div using jquery. </p> <p>Once the user clicks one of the results, they are redirected to the details page. When I click back from that page it doesnt load says form submission error. </p> <p>Not sure what to be looking for all the stuff I have seen is for when there are simply multiple ajax pages in one page. </p>
30,070,685
0
<p>I have had similar problem because I was not adding the <strong><em>_id</em></strong> column to the projection argument, so adding <strong><em>_id</em></strong> to the projections argument of the query was the solution. (<em>commented by @nobugs</em>) </p> <hr> <p>Example: </p> <pre><code> String[] projections = {"_id", "name", "age"}; Cursor cursor = db.query(domainClass.getSimpleName(), projections, null, null, null, null, null); </code></pre>
2,230,420
0
<p>I've not tested this, but I think you can request the page using ajax and check the response code - if there's no errors and the status code is 200 then the page is accessible.</p>
13,142,537
0
<p>First, replace <code>cat $strLocalDir"config.txt"</code> by <code>cat "${strLocalDir}config.txt"</code>.</p> <p>Then, check what does config.txt contains ? This will be moved to the $URLS variable, maybe it s not well formed.</p> <p>When you have such problems try to insert debug statements, like print. Test the value of your variables each time they're needed, you'll know more precisely where does the code fail.</p>
9,976,087
0
<p>try:</p> <pre><code>var mySelect = document.getElementById('select_value'); mySelect.getElementsByTagName('option')[index].setAttribute('selected','selected'); </code></pre> <p>where index stands for the position of the option you want to select.</p>
38,931,066
1
TypeError: string indices must be integer <p>I tried to get data from <code>JSON</code>. But instead data i get <code>TypeError</code>:</p> <pre><code>'TypeError: string indices must be integers' </code></pre> <p>Here ist my code:</p> <pre><code>api.authenticate(LOGIN, CONN) profil = api.get_profile("abc") data = json.dumps(profil, indent=4) print(data["login"]) </code></pre> <p>JSON file:</p> <pre><code>{ "public_email": "", "violation_url": null, "is_blocked": false, "links_published": 0, "login": "abc", "links_added": 1, "gg": "", "signup_date": "2014-10-26 21:15:41", } </code></pre> <p>I've looking for solution (google, SO) but I cannot find or not working for me.</p>
10,812,330
0
<p>All styleable attributes are here: <a href="http://developer.android.com/reference/android/R.styleable.html" rel="nofollow">http://developer.android.com/reference/android/R.styleable.html</a></p> <p>All styles (themes) are here: <a href="http://developer.android.com/reference/android/R.style.html" rel="nofollow">http://developer.android.com/reference/android/R.style.html</a></p>
12,355,086
0
What's the usage of tesseract useROI method? <p>Is there a documentation for tesseract dotnetwrapper? as in like a java doc or something? I'm trying to understand what this useROI method does?</p>
3,487,744
0
In PL/sql oracle stored procedure,trying to use analytical functions <p>Is it better to use cursor or analytical functions in a stored procedure for performance improvement?</p>