pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
27,319,280
0
<pre><code> while(token != NULL){ printf("%s\n", token); token = strtok(NULL, space); } </code></pre> <p>The while loop will fail when the token is <code>NULL</code>. At this time you are trying to print this pointer using your second <code>printf()</code> in the while loop which will lead to undefined behavior.</p> <p>Get rid of your second <code>printf()</code></p>
8,195,546
0
Applying jQuery Fade in or Scroll Effect to Facebook Like Newsfeed <p>I have a news feed that has been developed using PHP, MySQL, and jQuery. The news feed does it's job by getting new content every 5 seconds. However, this is done by a "refresh" of the complete content. I want to only ADD any new content to the news feed. I want a fade in or scroll effect to be used (jQuery) for this to occur. The items already loaded should stay on the feed and NOT reload with any new content. How can I do this?</p> <p>Here are my 2 pages and code.</p> <p>feed.php</p> <pre><code> &lt;body &gt; &lt;script&gt; window.setInterval(function(){ refreshNews(); }, 5000); &lt;/script&gt; &lt;div id="news"&gt;&lt;/div&gt; &lt;script&gt; function refreshNews() { $("#news").fadeOut().load("ajax.php", function( response, status, xhr){ if (status == "error"){ } else { $(this).fadeIn(); } }); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>ajax.php</p> <pre><code>&lt;?php require_once('../../Connections/f12_database_connect.php'); ?&gt; &lt;?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION &lt; 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } mysql_select_db($database_f12_database_connect, $f12_database_connect); $query_newsfeed_q = "SELECT * FROM newsfeed ORDER BY pk DESC"; $newsfeed_q = mysql_query($query_newsfeed_q, $f12_database_connect) or die(mysql_error()); $row_newsfeed_q = mysql_fetch_assoc($newsfeed_q); $totalRows_newsfeed_q = mysql_num_rows($newsfeed_q); ?&gt; &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;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;table border="1"&gt; &lt;tr&gt; &lt;td&gt;pk&lt;/td&gt; &lt;td&gt;title&lt;/td&gt; &lt;td&gt;content&lt;/td&gt; &lt;/tr&gt; &lt;?php do { ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $row_newsfeed_q['pk']; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row_newsfeed_q['title']; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row_newsfeed_q['content']; ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php } while ($row_newsfeed_q = mysql_fetch_assoc($newsfeed_q)); ?&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; &lt;?php mysql_free_result($newsfeed_q); ?&gt; </code></pre>
7,387,938
0
Modifying an existing MVVM infrastructure by adding View State feature <p>I'm going to introduce View State feature in the existing MVVM WPF Application. The objective is to be able to Save and Load (restore) particular state of a control.</p> <p>The question is more about design and best solution from system flexibility/maintability perspectives.</p> <p><strong>Current infrastructure:</strong></p> <pre class="lang-cs prettyprint-override"><code>public abstract class ViewModelBase { protected ViewModelBase(...) { } } // and few more very the same ViewModel classes for different control types public sealed class GridViewModel : ViewModelBase { protected GridViewModel(...) : base(...) { } } </code></pre> <p>I'm introduced <code>IViewState interface</code> so each specific ViewModel could provide own implementation like <code>GridViewState class</code> and going to put it in ViewModel infrastructure in following way: (Idea is to pass type of ViewState as generic parameter)</p> <pre class="lang-cs prettyprint-override"><code>public abstract class ViewModelBase&lt;TViewState&gt; where TViewState : class, IViewState { protected ViewModelBase(...) { } public TViewState ViewState { ... } } </code></pre> <ol> <li>Is it a good idea to attach View State feature to ViewModel?</li> <li>Is it a good solution to introduce tied relation between specific ViewModel typa and ViewState through the generic Type parameter like <code>class GridViewModel&lt;GridViewState&gt;</code>?</li> <li>Where and why better to define such methods like <code>LoadState() / SaveState(),</code> <code>IViewState</code> itself or <code>ViewModelBase</code>?</li> <li>Are there another design solutions?</li> </ol>
20,622,260
0
Format of datasource view <p>I have datagridview with sqlite connection. Here is the code:</p> <pre><code> dataGridView.AutoGenerateColumns = false; SQLiteConnection connection = new SQLiteConnection(string.Format("Data Source=data;"); connection.Open(); string sql = "SELECT * FROM users"; DataSet DS = new DataSet(); SQLiteDataAdapter DA = new SQLiteDataAdapter(sql, connection); DA.Fill(sqlDS); dataGridView.DataSource = DS.Tables[0].DefaultView; dataGridView.Update(); </code></pre> <p>I have datagridview with propertyName of columns like name in header table of sqlite. So data automatically insert in same name columns of datagridview.</p> <p>I have question: How I can format data in columns? For example: I have a column with header name: "Date". Same name in table of sqlite. There only date, but I want to see: "This" + date + " day!"</p>
14,492,518
0
CSS padding issue for vertically centered text <p>I've been trying to work this out all day long</p> <p>I've got a script for some jQuery dropdowns for my form, but the text within the drop down is not centered vertically in the box. I've styled the normal text boxes with <code>padding-bottom</code> so that the text sits in the middle, but I simply cannot do the same with the jQuery boxes. I have managed to do it on the actual dropdown, just not the option you see selected. If anyone could help get the text centered vertically in the box (not text align center) I will appreciate it.</p> <p><a href="http://fifamatchgenerator.com/dev/formtest/form1.php" rel="nofollow">http://fifamatchgenerator.com/dev/formtest/form1.php</a></p> <p>I think I have been staring at it for too long and become blind to it...</p> <p>p.s. there might be some code in the dd.css file which is what I have tried and failed with (most of the code is the default code which came with the script)</p>
37,717,699
0
azure-cli login getting "self signed certificate in certificate chain" <p>I have installed azure-cli via <code>npm install -g azure-cli</code> but and am getting <code>self signed certificate in certificate chain</code>:</p> <p><a href="https://i.stack.imgur.com/skvDv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/skvDv.png" alt="enter image description here"></a></p> <p>Any hints appreciated.</p>
19,040,334
0
<p>I was having the same problem, that is, the first time the image was saved correctly on the database side, but if subsequently validation failed and then I tried to save the image again after entering valid data I would get <code>0x</code> in the image column. To solve that I did what <a href="http://stackoverflow.com/questions/14943333/cant-save-binary-data-to-database-in-c-sharp#comment21040844_14943333">@Ann L.</a> said:</p> <pre><code>byte[] photo = null; if(model.Photo != null) { var stream = model.Photo.InputStream; stream.Position = 0; using(BinaryReader br = new BinaryReader(model.Photo.InputStream)) { photo = br.ReadBytes(model.Photo.ContentLength); } } </code></pre>
14,304,535
0
Display a table in a foreach loop with database values <p>I am trying to display a table in a while loop.. But I have got stuck there for 2 days. anyone can help me to do this? </p> <p>Now I will explain actually what I am trying to do here.. There are several categories and several subjects in my database. each category have its own subjects. Now I need to display category and its subjects as a list. When display subjects under particular category I need to add a HTML table with 2 columns to display subjects..</p> <p>This is the code that I have done so far.. </p> <pre><code> $categoryIds = implode(',', $_SESSION['category']); $q = "SELECT c. category_id AS ci, c.category_name AS cn, s.subject_name AS sn, s.subject_id AS si FROM category AS c INNER JOIN category_subjects AS cs ON cs.category_id = c.category_id INNER JOIN subjects AS s ON s.subject_id = cs.subject_id WHERE c.category_id IN ($categoryIds)"; $r = mysqli_query( $dbc, $q) ; $catID = false; $max_columns = 2; while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) { $categoryId = $row['ci']; $category = $row['cn']; $subjects = $row['sn']; echo '&lt;div&gt;'; //Detect change in category if($catID != $categoryId) { echo "&lt;h3&gt;Category 01: &lt;span&gt;{$category}&lt;/span&gt;&lt;span&gt;&lt;/span&gt;&lt;/h3&gt;\n"; foreach ( $subjects AS $sub ) { echo "&lt;div class='container'&gt;\n"; //echo "&lt;table&gt;&lt;tr&gt;\n"; //echo $sub; echo "&lt;/div&gt; &lt;!-- End .container DIV --&gt;\n"; } echo '&lt;/div&gt;'; } $catID = $categoryId; echo '&lt;/div&gt;'; } </code></pre> <p>Here, Category Name display correctly under tag. But problem is when going to display subjects which are belongs to categories. I am trying to display subjects table in .container Div. </p> <p>please Is anybody there can I get help whit this issue...? </p> <p>Thank you...</p>
12,446,067
0
<p>For sending mails using php mail function is used. But mail function requires SMTP server for sending emails. we need to mention SMTP host and SMTP port in php.ini file. Upon successful configuration of SMTP server mails will be sent successfully sent through php scripts.</p>
22,267,605
0
<p>if you want to remove the grey color in active buttons, just override it as follows:</p> <pre><code>.active{ background-color:white !important; } </code></pre> <p><em>note:</em></p> <blockquote> <p>And can you please let me know how I can get rid of the darker grey at the Top of the active class?</p> </blockquote> <p>well, if you are reffering to the highlighted button in the second image, it doesn't have active class, it's a non-active class. by setting all buttons as active initially,on first click it simply becomes inactive. You might want to think about what you are doing.</p> <p><strong>Update</strong> if you want to change the grey color you can do so by adding another class and toggling it as follows:</p> <pre><code>.select{ background-color:white !important; } $("div").children().click(function () { $(this).toggleClass("select"); }); </code></pre> <p>working <a href="http://jsfiddle.net/EFQHN/" rel="nofollow">fiddle</a></p>
40,359,217
0
I have created a simple website app wrapped via Cordova and Crosswalk and it displays a black screen when reopening <p>I have created a simple website app wrapped via Cordova and Crosswalk and it displays a black screen when reopening</p> <p>I used Intel XDK.</p> <p>When I open the app, it displays great. I can select button links to websites and even use the phone back button to go back to the main page.</p> <p>However when I close and reopen the app - it displays a black screen with a thin blue line on the left side. I have to close it thru the phone soft key app close button.</p> <p>I added this below but that does not seem to help either</p> <pre><code>function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } document.addEventListener("backbutton", onBackKeyDown, false); function onBackKeyDown() { // Handle the back button navigator.app.exitApp(); } </code></pre>
6,232,305
0
Cant get a control from a TabControl DataTemplate <p>I've been googling this for the last 2 days and cant get anywhere, I just cant do anything to any control in a datatemplate of a tabcontrol. </p> <p>First off, the code:</p> <pre><code>private void Window_Loaded(object sender, RoutedEventArgs e) { tabControl1.ItemsSource = new string[] { "TabA", "TabB", "TabC" }; } private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e) { ContentPresenter cp = tabControl1.Template.FindName("PART_SelectedContentHost", tabControl1) as ContentPresenter; DataTemplate dt = tabControl1.ContentTemplate; Grid g = tabControl1.ContentTemplate.FindName("myGrid", cp) as Grid; g.Background = new SolidColorBrush(Colors.Red); } </code></pre> <p>xaml</p> <pre><code>&lt;Window x:Class="tabTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded"&gt; &lt;Grid&gt; &lt;TabControl IsSynchronizedWithCurrentItem="True" Height="140" Name="tabControl1" Width="230" SelectionChanged="tabControl1_SelectionChanged"&gt; &lt;TabControl.ContentTemplate&gt; &lt;DataTemplate&gt; &lt;Grid x:Name="myGrid"&gt; &lt;/Grid&gt; &lt;/DataTemplate&gt; &lt;/TabControl.ContentTemplate&gt; &lt;/TabControl&gt; &lt;/Grid&gt; </code></pre> <p></p> <p>In short this line:</p> <pre><code>Grid g = tabControl1.ContentTemplate.FindName("myGrid", cp) as Grid; </code></pre> <p>throws an error "System.InvalidOperationException" This operation is valid only on elements that have this template applied.</p> <p>this particular idea i got from <a href="http://www.netframeworkdev.com/windows-presentation-foundation-wpf/accessing-elements-inside-a-datatemplate-27994.shtml" rel="nofollow">here</a></p> <p>I've found loads of other ways of doing this but I cant seem to get anywhere :( hope someone can point me in the right direction :)</p>
8,728,861
0
Can i specify a schema to build an XDocument while loading a xml file? <p>I am a xml newbie trying to create a XDocument type from a xml file.</p> <p>I can validate the xml against a schema.</p> <pre><code>public class XmlHandler { public XDocument Read(string filename, string schemaname) { var schemas = this.GetSchemas(schemaname); var doc = XDocument.Load(filename); var invalid = false; doc.Validate(schemas, (o, args) =&gt; { this.OnValidationErrors(o, args); invalid = true; }); return invalid ? new XDocument() : doc; } public XmlSchemaSet GetSchemas(string schemaname) { var schemas = new XmlSchemaSet(); schemas.Add(null, schemaname); return schemas; } private void OnValidationErrors(object sender, ValidationEventArgs e) { Debug.Print("Errors: ", e); } } </code></pre> <p>But the structure of the the XDocument seems to be wrong.</p> <p>When running this code</p> <pre><code> [Fact] public void Read_get_elements() { var sut = new XmlHandler(); var result = sut.Read(this.TestFile, this.TestFileSchema); var root = result.Root; var elements = result.Elements(); var nodes = result.Nodes(); var descendants = result.Descendants(); Assert.NotEmpty(elements); } </code></pre> <p>the root variable contains the complete xml string and the the other IEnumerable variables stay empty. What am i missing?</p> <p>EDIT: This is part of the xml and the xsd</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="https://www.eurexchange.com/members/releases/eurex14/manuals_technical_en.html" xmlns="https://www.eurexchange.com/members/releases/eurex14/manuals_technical_en.html" elementFormDefault="qualified"&gt; &lt;xs:include schemaLocation="eurex_reports_common_structs.xsd"/&gt; &lt;xs:complexType name="cb020Type"&gt; &lt;xs:annotation&gt; &lt;xs:documentation&gt;CB020 Position Summary&lt;/xs:documentation&gt; &lt;/xs:annotation&gt; &lt;xs:sequence&gt; &lt;xs:element name="rptHdr" type="rptHdrType" /&gt; &lt;xs:element name="cb020Grp" type="cb020GrpType" minOccurs="0" maxOccurs="unbounded" /&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;xs:element name="cb020" type="cb020Type"/&gt; &lt;xs:complexType name="cb020GrpType"&gt; &lt;xs:sequence&gt; &lt;xs:element name="cb020KeyGrp" type="cb020KeyGrpType" /&gt; &lt;xs:element name="cb020Grp1" type="cb020Grp1Type" minOccurs="1" maxOccurs="unbounded" /&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:schema&gt; </code></pre> <p>And this is part of the xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;cb020 xmlns="https://www.eurexchange.com/members/releases/eurex14/manuals_technical_en.html"&gt; &lt;rptHdr&gt; &lt;exchNam&gt;EUREX&lt;/exchNam&gt; &lt;envText&gt;P&lt;/envText&gt; &lt;rptCod&gt;CB020&lt;/rptCod&gt; &lt;rptNam&gt;Position Summary&lt;/rptNam&gt; &lt;membLglNam&gt;Cyberdyne Systems&lt;/membLglNam&gt; &lt;rptPrntEffDat&gt;2011-12-05&lt;/rptPrntEffDat&gt; &lt;rptPrntRunDat&gt;2011-12-05&lt;/rptPrntRunDat&gt; &lt;/rptHdr&gt; &lt;cb020Grp&gt; &lt;cb020KeyGrp&gt; ... &lt;/cb020KeyGrp&gt; &lt;cb020Grp1&gt; ... &lt;/cb020Grp1&gt; &lt;/cb020Grp&gt; &lt;/cb020&gt; </code></pre>
35,147,079
0
<p>You have to use Reflection, please look at</p> <p><a href="http://stackoverflow.com/questions/737151/how-to-get-the-list-of-properties-of-a-class">How to get the list of properties of a class?</a></p> <p>I added a new double? property at your class.</p> <pre><code> class Class1 { public int Age { get; set; } public string Family { get; set; } public string Name { get; set; } public double? d { get; set; } } [Test] public void MyTest() { Class1 c = new Class1() { Age = 12, Family = "JR", Name = "MAX" }; foreach (var prop in c.GetType().GetProperties().Where(x =&gt; x.PropertyType == typeof(double?))) { Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(c)); prop.SetValue(c, (double?)null); // set null as you wanted } } </code></pre>
20,103,326
0
<pre><code>url: $obj.url, </code></pre> <p>This parameter needs to be a string. If you want a dynamic url from your obj variable do this:</p> <pre><code>url: $obj+".php", // .php or whatever the file type is of the page you're requesting </code></pre>
15,785,466
0
<p>You do not need jQuery for this. In cases where jQuery really isn't needed, I don't really suggest it. At that point it's just kind of pointless. Use regular JS where possible, use jQuery where needed.</p> <pre><code>for (var i = 0; i &lt; pieData2.length; i++) { alert(pieData2[i].label + ' : ' + pieData2[i].value); } </code></pre> <p>If you really want to use jQuery, since <code>$.each</code> can iterate over arrays AND objects, you can just use it to iterate over the array and alert each.</p> <p>This will iterate over each object in the array and alert each key, value pair...</p> <pre><code>$.each(pieData2, function (key, obj) { alert(obj.label + ' : ' + obj.value); }); </code></pre> <p>If you need to iterate over the array and over each object (if you do not know the length), then you can do:</p> <pre><code>for (var i = 0; i &lt; pieData2.length; i++) { for (var prop in pieData2[i]) { if (pieData2[i].hasOwnProperty(prop)) { alert(prop + ' : ' + pieData2[i][prop]); } } } </code></pre> <p>or</p> <pre><code>$.each(pieData2, function(obj) { $.each(pieData2[obj], function(key, value) { alert(key + ' : ' + value); }); }); </code></pre>
515,828
0
<p>You need to wrap the textarea in an ItemTemplate tag for it to work:</p> <pre><code>&lt;asp:Repeater ID="NotesRepeater" runat="server" DataSourceID="SheetParams"&gt; &lt;ItemTemplate&gt; &lt;textarea style="clear:both; font-size:large" name="notes"&gt; &lt;%# Eval("Notes") %&gt; &lt;/textarea&gt; &lt;ItemTemplate&gt; &lt;/asp:Repeater&gt; </code></pre>
24,919,141
0
<p>Move the regex matching into a method.</p> <p>You could associate the regex with a key in a hash, too, making this easier, roughly:</p> <p>EMAILS = { "Berkeley": /\A[\w+-.]+@berkeley.edu\z/i, "Washington": /whatever/ }</p> <p>Iterate over the hash to get the value and regex:</p> <pre><code>EMAILS.each do |school, regex| # If it matches, return the `school` value end </code></pre> <p>Use the <em>same</em> method for your email validation by validating <code>:email</code> against the method instead of a simple regex as detailed in the <a href="http://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations" rel="nofollow">Custom Validation section of the Active Record Validations Guide</a>. You may need to tweak the return value etc. to get the function to work for both things, or write a thin wrapper for the validation around the lookup.</p> <p>Consider a callback to actually set the value, e.g., <code>:after_validation</code> or <code>:before_save</code>.</p>
17,903,742
0
<p>Here's a simple function that I use.</p> <pre><code>var pad=function(num,field){ var n = '' + num; var w = n.length; var l = field.length; var pad = w &lt; l ? l-w : 0; return field.substr(0,pad) + n; }; </code></pre> <p>For example:</p> <pre><code>pad (20,' '); // 20 pad (321,' '); // 321 pad (12345,' '); //12345 pad ( 15,'00000'); //00015 pad ( 999,'*****'); //**999 pad ('cat','_____'); //__cat </code></pre>
11,270,536
0
Debug sales order workflow in OpenERP 6.1 web client <p>I'm testing out the OpenERP 6.1 web client, and I sometimes have a sales order or other kind of document that gets stuck for some reason. I want to be able to look at the workflow diagram for this document to see exactly where it is stuck.</p> <p>One example that happened to me was a sales order that had shipped and the invoice was paid, but the sales order still wasn't done. After some digging, I found that one of the procurements was still running.</p> <p>I can still print the workflow from the GTK client, but isn't there some way to print it from the web client?</p> <p>I found a couple of ways to get at the screen that lets me edit the workflow, but that's not what I'm looking for. I want to print the diagram that shows the current state of the workflow instance for the open document.</p>
20,353,639
0
<p>The tool "uchardet" does this well using character frequency distribution models for each charset. Larger files and more "typical" files have more confidence (obviously).</p> <p>On ubuntu, you just <code>apt-get install uchardet</code>. </p> <p>On other systems, get the source, usage &amp; docs here: <a href="https://github.com/BYVoid/uchardet" rel="nofollow">https://github.com/BYVoid/uchardet</a></p>
36,029,791
0
<p>Try </p> <pre><code> Dim data As Range Set data = Intersect(Sheet2.Columns("O"), Sheet2.UsedRange) data.NumberFormat = "mm/dd/yyyy" </code></pre>
15,988,549
0
<p>You're trying to ceil an array, you can do it on a numeric value.</p> <p>Try editing your query like this:</p> <pre><code>$query = "SELECT COUNT(id) AS tot FROM actiongame"; </code></pre> <p>And then your PHP code like this:</p> <pre><code>$total_records = $row['tot']; </code></pre>
2,314,412
0
<p>Instead of :</p> <pre><code>if len(line) &lt;= 1: # only '\n' in «empty» lines break values = line.split() </code></pre> <p>try this:</p> <pre><code>values = line.split() if not values: # line is wholly whitespace, end of segment break </code></pre>
3,323,900
0
Passing double types to ceil results in different values for different optimization levels in GCC <p>Below, the result1 and result2 variable values are reporting different values depending upon whether or not you compile the code with -g or with -O on GCC 4.2.1 and on GCC 3.2.0 (and I have not tried more recent GCC versions):</p> <pre><code>double double_identity(double in_double) { return in_double; } ... double result1 = ceil(log(32.0) / log(2.0)); std::cout &lt;&lt; __FILE__ &lt;&lt; ":" &lt;&lt; __LINE__ &lt;&lt; ":" &lt;&lt; "result1==" &lt;&lt; result1 &lt;&lt; std::endl; double result2 = ceil(double_identity(log(32.0) / log(2.0))); std::cout &lt;&lt; __FILE__ &lt;&lt; ":" &lt;&lt; __LINE__ &lt;&lt; ":" &lt;&lt; "result2==" &lt;&lt; result2 &lt;&lt; std::endl; </code></pre> <p>result1 and result2 == 5 only when compiling using -g, but if instead I compile with -O I get result1 == 6 and result2 == 5.</p> <p>This seems like a difference in how optimization is being done by the compiler, or something to do with IEEE floating point representation internally, but I am curious as to exactly how this difference occurs. I'm hoping to avoid looking at the assembler if at all possible.</p> <p>The above was compiled in C++, but I presume the same would hold if it was converted to ANSI-C code using printfs.</p> <p>The above discrepancy occurs on 32-bit Linux, but not on 64-bit Linux.</p> <p>Thanks bg</p>
10,967,882
0
<p>When communicating with TCP or UDP, the socket is distinguished by a 4-tuple:</p> <ul> <li>local address</li> <li>local port</li> <li>remote address</li> <li>remote port</li> </ul> <p>If you leave the local assignment alone, and you are communicating with a connected protocol, the <code>connect</code> call will find an available local port for you. If you are restricted to a particular range of ports, then you'll need to do local address and port binding. However, in that case, since each process is only handling a single connection, I would just assign each process a unique port when it is started, rather than having it try to find an available one.</p> <p>That is, assuming there is a single process responsible for starting all the other processes, that single process would decide which port should be used by the process it is about the start. This is simpler because the decision is made by a single entity, so it can use a simple algorithm, like:</p> <pre><code>for (unsigned short p = minPort; p &lt; maxPort; ++p) { child_pid = startWorker(p); child_pid_map[child_pid] = p; } </code></pre> <p>If the child dies, the starter process can consult the <code>child_pid_map</code> to reuse that port immediately.</p> <p>If using an external agent to assign ports is not possible, the simplest technique is to just attempt a <code>bind</code> call to a random port in the range. If it fails with <code>EADDRINUSE</code>, then incrementally try the next port number in the sequence (wrapping if necessary) until success is achieved, or you have tried all the ports.</p>
22,632,862
0
<p>There are events like GotFocus and LostFocus for controls.</p> <p>If you subscribe to these events they automatically get called when your input receives or looses focus</p> <p>you can use those events for your purpose.</p> <p>XAML Declaration</p> <pre><code>&lt;TextBox Name="myTextbox" GotFocus="myTextbox_GotFocus" /&gt; </code></pre> <p>and inside the cs</p> <pre><code> private void myTextbox_GotFocus(object sender, RoutedEventArgs e) { } private void ContentPanel_LostFocus(object sender, RoutedEventArgs e) { } </code></pre>
36,379,539
0
Rails 4 devise_invitable "The invitation token provided is not valid!" error <p>I have been following Ryan Boland's Rails multitenancy tutorial, but have run into a snag with devise_invitable. </p> <p>I create a new account and user/account owner on a chosen subdomain (mysubdomain.lvh.me:3000), from which I can send a user invitation just fine. I open the invitation link in an incognito Chrome session to ensure I am not logged in or have any current session. Upon clicking on the invitation link, I am redirected to the sign in page (mysubdomain.lvh.me:3000/users/sign_in) and see a flash notice: "The invitation token provided is not valid!"</p> <p>Related to this one:</p> <p><a href="http://stackoverflow.com/questions/25703460/rails-4-devise-invitable-invitation-token-invalid/36379472?noredirect=1#comment60376301_36379472">Rails 4 devise_invitable invitation token invalid</a></p>
22,248,851
0
<h1>Bulk Binds (BULK COLLECT &amp; FORALL) and Record Processing in Oracle</h1> <p>Although this topic involves a much larger discussion of how to optimize database DML operations for large record sets, this approach is applicable for variable magnitudes of record volumes and even has a nice feature set, which includes a DML option called <strong>SAVE EXCEPTIONS</strong>, which enables a database operation to SKIP and continue past individual DML transactions that have encountered EXCEPTIONS.</p> <p>I have adapted a script and added some additional explanatory notation to show how this works. If you would like some additional reading from the source I used, see the following link for a discussion on <a href="http://www.oracle-base.com/articles/9i/bulk-binds-and-record-processing-9i.php#save_exceptions" rel="nofollow noreferrer">Oracle DML Bulk Binds and Record Processing</a>.</p> <h2>The Sample Table: exception_test</h2> <p>Use the DDL Below to create the test table used to store the data from our procedure's Bulk Binding DML commands:</p> <pre><code>CREATE TABLE "EXCEPTION_TEST" ( "ID" NUMBER(15,0) NOT NULL ENABLE, CONSTRAINT "EXCEPTION_TEST_PK" PRIMARY KEY ("ID") ENABLE ) / </code></pre> <p>The Primary Key is the single column. It has an assigned NOT NULL constraint which will be the property used later for generating several exceptions.</p> <h2>Stored Procedure: proc_exam_save_exceptions</h2> <pre><code>create or replace PROCEDURE proc_exam_save_exceptions IS -- Declare and Instantiate Data Types TYPE t_tab IS TABLE OF exception_test%ROWTYPE; l_tab t_tab := t_tab(); l_error_count NUMBER; ex_dml_errors EXCEPTION; PRAGMA EXCEPTION_INIT(ex_dml_errors, -24381); BEGIN -- Fill the collection. FOR i IN 1 .. 2000 LOOP l_tab.extend; l_tab(l_tab.last).id := i; END LOOP; -- Cause a failure or two. l_tab(50).id := NULL; l_tab(51).id := NULL; l_tab(1250).id := NULL; l_tab(1252).id := NULL; EXECUTE IMMEDIATE 'TRUNCATE TABLE exception_test'; -- Perform a bulk operation. BEGIN FORALL i IN l_tab.first .. l_tab.last SAVE EXCEPTIONS INSERT INTO exception_test VALUES l_tab(i); EXCEPTION WHEN ex_dml_errors THEN l_error_count := SQL%BULK_EXCEPTIONS.count; DBMS_OUTPUT.put_line('Number of failures: ' || l_error_count); FOR i IN 1 .. l_error_count LOOP DBMS_OUTPUT.put_line('Error: ' || i || ' Array Index: ' || SQL%BULK_EXCEPTIONS(i).error_index || ' Message: ' || SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE)); END LOOP; END; END; </code></pre> <p>​</p> <p>The first loop instantiates a collection type variable (nested table) and initializes it with a non-null value. Note the block of this procedure:</p> <pre><code>-- Cause a failure or two. l_tab(50).id := NULL; l_tab(51).id := NULL; l_tab(1250).id := NULL; l_tab(1252).id := NULL; </code></pre> <p>Which changes index positions 50, 51, 1250 and 1252 with a NULL value to force a DML error against the table constraint of the ID column on table <em>exception_test</em>. Compiling this procedure and executing it from the command line reveals in the DBMS OUT display a feedback message identifying the DML operations that failed by an internal count of each loop iteration...</p> <h2>Testing the Stored Procedure</h2> <p>Call the procedure to iterate through the defined DML loops and verify the BULK EXCEPTION HANDLING feature at work.</p> <pre><code>-- Command to Call Procedure begin proc_exam_save_exceptions(); end; </code></pre> <p>The following is the output of this procedure's execution:</p> <pre><code>Number of failures: 4 Error: 1 Array Index: 50 Message: ORA-01400: cannot insert NULL into () Error: 2 Array Index: 51 Message: ORA-01400: cannot insert NULL into () Error: 3 Array Index: 1250 Message: ORA-01400: cannot insert NULL into () Error: 4 Array Index: 1252 Message: ORA-01400: cannot insert NULL into () Statement processed. 0.05 seconds </code></pre> <p>An additional query of the target table shows that DML errors introduced in the middle of the loop iterations did not interrupt the completion of the other loops and their assigned DML operation.</p> <p><img src="https://i.stack.imgur.com/Vy0e4.jpg" alt="Sample Verification of Skipped Exception Values"></p> <h2>Additional Notes and Discussion</h2> <p>Here are some parting notes to keep in mind when using the <strong>SAVE EXCEPTIONS</strong> Bulk DML option:</p> <ol> <li><p>The meta information in the <em>error_index</em> value of the resulting collection: <strong>SQL%BULK_EXCEPTIONS</strong> is based on the count of loop iterations from the initial cursor query of the data.</p> <p>i.e., You will still need to correlate in some way that the error in loop iteration #51 (error_index = 51) lines up with whatever identifying key exists in your actual DML target tables. I recommend at least using ORDER BY clauses carefully and consistently in your DML cursors so that your loop iterations are consistently matched with the same index/key values.</p></li> <li><p>There are some additional extensions to the functionality of the SAVE EXCEPTIONS and BULK DML handling alternatives that may prove to serve additional utility above traditional approaches to large volume DML operations. Among them includes: error threshold limitations (i.e., quit when a pre-defined number of DML exceptions are handled) and Bulk Processing loop size definitions. </p></li> </ol>
27,909,576
0
How to model mongodb collections for Cassandra database (migration)? <p>I am new to Cassandra and trying migrate my App from MongoDB to Cassandra</p> <p>I have the following collections in MongoDB</p> <pre><code>PhotoAlbums [ {id: oid1, title:t1, auth: author1, tags: ['bob', 'fun'], photos: [pid1, pid2], views:200 } {id: oid2, title:t2, auth: author2, tags: ['job', 'fun'], photos: [pid3, pid4], views: 300 } {id: oid3, title:t3, auth: author3, tags: ['rob', 'fun'], photos: [pid2, pid4], views: 400 } .... ] Photos [ {id: pid1, cap:t1, auth: author1, path:p1, tags: ['bob','fun'], comments:40, views:2000, likes:0 } {id: pid2, cap:t2, auth: author2, path:p2, tags: ['job','fun'], comments:50, views:50, likes:1, liker:[bob] } {id: pid3, cap:t3, auth: author3, path:p3, tags: ['rob','fun'], comments:60, views: 6000, likes: 0 } ... ] Comments [ {id: oid1, photo_id: pid1, commenter: bob, text: photo is cool, likes: 1, likers: [john], replies: [{rep1}, {rep2}]} {id: oid2, photo_id: pid1, commenter: bob, text: photo is nice, likes: 1, likers: [john], replies: [{rep1}, {rep2}]} {id: oid3, photo_id: pid2, commenter: bob, text: photo is ok, likes: 2, likers: [john, bob], replies: [{rep1}]} ] </code></pre> <p><strong>Queries:</strong></p> <ul> <li><p>Query 1: Show a list of popular albums (based on number of likes)</p></li> <li><p>Query 2: Show a list of most discussed albums (based on number of comments) </p></li> <li><p>Query 3: Show a list of all albums of a given author on user's page </p></li> <li><p>Query 4: Show the album with all photos and all comments (pull album details, show photo thumbnails of all photos in the album, show all comments of selected photo </p></li> <li><p>Query 5: Show a list of related albums based on the tags of current album</p></li> </ul> <p><strong>Given the above schema and requirements, how should I model this in Cassandra?</strong></p>
6,884,628
0
C with assembly tutorials <p>Please, advice me manuals or tutorials by joint usage C language with assembly in Unix systems.</p> <p>Thank you.</p>
20,810,732
0
<p>According to <a href="http://flask.pocoo.org/docs/api/#flask.url_for" rel="nofollow"><code>url_for</code> documentation</a>:</p> <blockquote> <p>If the value of a query argument is None, the whole pair is skipped.</p> </blockquote> <p>Make sure that <code>url_title</code> is not <code>None</code>.</p> <p>Or specify default value for <code>url_title</code> in the <code>artitle_page</code> function.</p>
234,953
0
<p>I think it depends on how if/how you plan to expand upon your data model. For instance, what if you decided that you not only want to have User Events, but also, Account Events, or Login Events, and User, Accounts, and Logins are all different types of entities, but they share some Events. In that case, you would might want a normalized database model:</p> <ul> <li>Users (Id int, Name varchar)</li> <li>Accounts (Id int, Name varchar)</li> <li>Logins (Id int, Name varchar)</li> <li>Events (Id int, Name varchar)</li> <li>UserEvents (UserId int, EventId int)</li> <li>AccountEvents (AccountId int, EventId int)</li> <li>LoginEvents (LoginId int, EventId int)</li> </ul>
38,758,259
0
<p>You can name the function used at <code>.then()</code>, recursively call same function at <code>.then()</code> of <code>doSomethingAsync()</code> call until <code>state == "finish"</code></p> <pre><code>// name function used at `.then()` somePromise.then(function re(data) { if(state == "finish") { return data; }; // DoSomething async then repeat these codes // call `re` at `.then()` chained to `doSomethingAsync()` doSomethinAsync(data).then(re); }).then((data) =&gt; console.log("finish", data)); </code></pre> <p>See also <a href="http://stackoverflow.com/questions/38034574/multiple-sequential-fetch-promise/">multiple, sequential fetch() Promise</a></p>
39,049,541
0
<p>Additionally, consider <a href="https://www.w3.org/Style/XSL/" rel="nofollow">XSLT</a>, the special purpose transformation language that can directly transform XML to CSV even parsing from other XML files using its <code>document()</code> function. Python's <a href="http://lxml.de/" rel="nofollow">lxml</a> module can process XSLT 1.0 scripts. Be sure all three xmls reside in same directory.</p> <p><strong>XSLT</strong> Script <em>(save as .xsl file --a special .xml file-- to be called below in Python)</em></p> <pre><code>&lt;xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"&gt; &lt;xsl:output version="1.0" encoding="UTF-8" method="text" indent="yes" omit-xml-declaration="yes"/&gt; &lt;xsl:strip-space elements="*"/&gt; &lt;xsl:template match="/projects"&gt; &lt;xsl:copy&gt; &lt;xsl:text&gt;Pid,Clientid,ClientName,ClientActive,ProjectName,ProjectActive,Billable,BillBy,HourlyRate,&lt;/xsl:text&gt; &lt;xsl:text&gt;Budget,OverbudgetNotificationPercentage,CreatedAt,UpdatedAt,StartsOn,EndsOn,Estimate,EstimateBy,&lt;/xsl:text&gt; &lt;xsl:text&gt;Notes,CostBudget,TeammemberName1,CostRate1,TeammemberName2,CostRate2,TeammemberName3,CostRate3,&lt;/xsl:text&gt; &lt;xsl:text&gt;TaskId1,TotalHours1,TaskId2,TotalHours2&amp;#xa;&lt;/xsl:text&gt; &lt;xsl:apply-templates select="project"/&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;xsl:template match="project"&gt; &lt;xsl:variable name="clientid" select="client-id"/&gt; &lt;xsl:value-of select="concat(id, ',')"/&gt; &lt;xsl:variable name="delimiter"&gt;&lt;xsl:text&gt;&amp;quot;,&amp;quot;&lt;/xsl:text&gt;&lt;/xsl:variable&gt; &lt;xsl:for-each select="document('clients.xml')/clients/client[id=$clientid]/* [local-name()='id' or local-name()='name' or local-name()='active']"&gt; &lt;xsl:value-of select="." /&gt; &lt;xsl:if test="position() != last()"&gt; &lt;xsl:text&gt;,&lt;/xsl:text&gt; &lt;/xsl:if&gt; &lt;/xsl:for-each&gt; &lt;xsl:value-of select="concat(',',name,',',active,',',billable,',',bill-by,',',hourly-rate,',',budget,',', over-budget-notification-percentage,',',created-at,',',updated-at,',',starts-on,',',ends-on,',', estimate,',',estimate-by,',',notes,',',cost-budget,',')"/&gt; &lt;xsl:for-each select="document('teammembers.xml')/root/team_members/item[cid=$clientid]/* [local-name()='full_name' or local-name()='cost_rate']"&gt; &lt;xsl:if test="position() &amp;lt; 5"&gt; &lt;xsl:value-of select="." /&gt; &lt;xsl:text&gt;,&lt;/xsl:text&gt; &lt;/xsl:if&gt; &lt;/xsl:for-each&gt; &lt;xsl:for-each select="document('ClientItems_teammembers.xml')/root/tasks/item[cid=$clientid]/* [local-name()='task_id' or local-name()='total_hours']"&gt; &lt;xsl:if test="position() &amp;lt; 5"&gt; &lt;xsl:value-of select="." /&gt; &lt;xsl:if test="position() != last()"&gt; &lt;xsl:text&gt;,&lt;/xsl:text&gt; &lt;/xsl:if&gt; &lt;/xsl:if&gt; &lt;/xsl:for-each&gt; &lt;xsl:text&gt;&amp;#xa;&lt;/xsl:text&gt; &lt;/xsl:template&gt; &lt;/xsl:transform&gt; </code></pre> <p><strong>Python</strong> script <em>(transforming projects.xml and reading in other two in XSLT)</em></p> <pre><code>import lxml.etree as ET def transformXML(): dom = ET.parse('projects.xml') xslt = ET.parse('XSLTscript.xsl') transform = ET.XSLT(xslt) newdom = transform(dom) with open('Output.csv'),'w') as f: f.write(str(newdom)) if __name__ == "__main__": transformXML() </code></pre> <p><strong>Output</strong></p> <pre><code>Pid,Clientid,ClientName,ClientActive,ProjectName,ProjectActive,Billable, BillBy,HourlyRate,Budget,OverbudgetNotificationPercentage,CreatedAt, UpdatedAt,StartsOn,EndsOn,Estimate,EstimateBy,Notes,CostBudget,TeammemberName 1,CostRate1,TeammemberName2,CostRate2,TeammemberName3,CostRate3, TaskId1,TotalHours1,TaskId2,TotalHours2 11493770,4708336,AFB,true,Services - Consulting - AH,true,true,Project, 421.28,16.0,80.0,2016-08-16T03:22:51Z, 2016-08-16T03:22:51Z,,,16.0,project,Random notes,,BobR,76.0,BobR,76.0,BobR,76.0,6357137,0.0,6357138,0.0, </code></pre>
3,543,373
0
<p>The Base.cs file looks like this.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Agatha.Common; public abstract class BaseRequest :Request { public string UserName { get; set; } public string UserDomainName { get; set; } public string ClientLanguageCode { get; set; } public DateTime ClientCreated { get; set; } public DateTime ClientSent { get; set; } public DateTime ServerReceived { get; set; } public DateTime ServerProcessed { get; set; } public void BeforeSend(IUserContext context) { ClientSent = DateTime.UtcNow; UserName = context.UserName; UserDomainName = context.UserDomainName; ClientLanguageCode = context.LanguageCode; } } public abstract class BaseResponse : Response { public DateTime ServerCreated { get; set; } public DateTime ServerProcessed { get; set; } public string[] ValidationErrors { get; set; } public bool IsValid { get { return Exception == null &amp; !ValidationErrors.Any(); } } } </code></pre>
22,814,545
0
Adding time to curdate mysql <p>I have two columns, one is a datetime, and another is a time. I need to add to the time column the CURDATE(), and compare with the datetime column.</p> <pre><code>SELECT b.rese_data, a.period_ini, a.period_end FROM esp_time a, rese b WHERE a.week_day = WEEKDAY(NOW()) AND a.period_ini &lt;= NOW() AND a.period_end &gt;= NOW() AND b.rese_data &gt;= a.periodo_ini AND b.rese_data &lt;= a.periodo_fim </code></pre> <p>First i select the two period(time) which can be like :</p> <pre><code>period_ini = "12:00:00" pediod_end = "17:00:00" </code></pre> <p>and then compare with the rese_data(datetime)</p>
19,306,013
0
<p>The garbage-collector does not identify and examine garbage, except perhaps when processing the Large Object Heap. Instead, its behavior is like a that of a bowling-alley pinsetter removing deadwood between throws: the pinsetter grabs all the pins that are still standing, lifts them off the surface of the lane, and then runs the sweeper bar across the lane without regard for how many pins are on that surface. Sweeping out memory wholesale is much faster than identifying individual objects to be deleted. If 1% of objects have finalizers (the real number's probably even less), then it would be necessary to examine 100 object headers to find each finalizable object. Having a separate list of objects which have finalizers makes it unnecessary for the GC to even look at any garbage objects that don't.</p>
5,210,420
0
<p>make history and queue tables ? edits go to queue table and if admin aproves queue->real->history...</p>
26,357,528
0
<pre><code>window.attachEvent("onmouseout", popUp); </code></pre> <p>you lost 'on'</p>
26,479,504
0
How to parse milliseconds using Data.Time in Haskell <p>I have a formatted time strings from a log file of the form "08:14:59,012" and I would like to parse them as UTCTime (to be able to make some time difference and comparison operations).</p> <p>I'm unable to find a way to parse the milliseconds. Here's what I have so far</p> <pre><code>import System.Locale (defaultTimeLocale) import Data.Time (UTCTime) import Data.Time.Format (readTime) readHMS :: String -&gt; UTCTime readHMS = readTime defaultTimeLocale "%H:%M:%S" -- ^^ How to parse milis? ""%H:%M:%S,%Q" doesn't work test = readHMS "08:14:59,012" </code></pre> <p>Please suggest a way to parse milliseconds so that the test above contains them.</p>
13,404,622
0
<p>Just pass in the function you want to be unique. Like this:</p> <pre><code>function reusableFunc(fn) { //reused code block here fn(); //reused code block here } var myResuableFunc1 = function (args) { reusableFunc(function () { //do your business here. }); }; var myResuableFunc2 = function (args) { reusableFunc(function () { //do your business here. }); }; //Or another way function myResuableFunc3(args) { reusableFunc(function () { //do your business here }); } </code></pre> <p>Then, you can create as many functions using the shared code as you want and, through the power of closures, pass these newly created functions around any way that you like.</p>
20,240,426
0
<p>seems to be linked with native library provided by Apple.</p> <p>I've fixed this problem by reinstall ruby.</p> <pre><code>rvm reinstall 2.0.0-p247 --disable-binary --autolibs=3 </code></pre>
15,235,134
0
<p>You can't group inline except with an aggregate (min, max, sum, count) etc. Otherwise you are going to get the first result something is grouped on and have inaccuracies. </p> <p>Can you just collapse the values of the grouping instead? </p> <p>In SSRS generally with reports you have a 'details' grouping whether it is a matrix or a table report. You mentioned 'columns' so it sounds like you have header's of A, B, and C and they want to see a totals. You can generally add a grouping but then have it collapse or expand on demand. That way you present an end user with the data but they have the option of expanding it to see more if they want.</p> <p>Since you did not specify if you have a matrix I will assume you have one. When you have multiple categories you can hit the grouping of a row or column and if you are having a matrix it is probably using a [SUM(field)]. The grouping of columns are showing all of them, however you can specify they are collapsed or expanded at runtime. Right Click the grouing and you get 'Group Properties'. Select the 'Visibility' pane on the left. Choose 'Hide' radio button and the default for your report will 'collapse' the values to be an aggregate instead of the expanded details of each column. If you want an option to have the user expand or collapse select the checkbox 'Display can be toggled by this report item:'. Choose a textbox or other object outside the collected scope and a user can be presented with the option to collapse or expand on default.</p>
15,309,943
0
<p>It's not safe to do it your way, since there may also be \r or \n in a SQL statement (e.g. a long TEXT with many lines).</p> <p>If you're sure there aren't case like that, I'd suggest you to use <a href="http://www.php.net/trim" rel="nofollow">trim()</a> instead of <a href="http://www.php.net/str_replace" rel="nofollow">str_replace()</a>. It'll remove all spaces and EOL at the end of each lines.</p> <pre><code>&lt;?php $tmp = trim($line); ?&gt; </code></pre> <p>You may also specify to ONLY REMOVE EOL (both "\r\n" and "\n") like this:</p> <pre><code>&lt;?php $tmp = trim($line, "\r\n"); ?&gt; </code></pre>
411,660
0
Enterprise Library Unity vs Other IoC Containers <p>What's pros and cons of using Enterprise Library Unity vs other IoC containers (Windsor, Spring.Net, Autofac ..)?</p>
5,527,895
0
<p>I'll explain my short story with R and big data set.<br> I had a connector from R to RDBMS, </p> <ul> <li>where I stored 80mln compounds.</li> </ul> <p>I've build a queries which gathered some subset of this data.<br> Then manipulate on this subset.<br> R was simply choking with more than <strong>200k</strong> rows in memory on my PC. </p> <ul> <li>core duo</li> <li>4 GB ram</li> </ul> <p>So working on some appropriate subset for machine is good approach.</p>
35,671,543
0
<p>Try using <code>$.when.apply()</code> , a single <code>.done()</code></p> <pre><code>$.when.apply($, [request, request2]) .done(function(output, output2) { // do stuff with responses from `request`, `request2` if (output[0].result === "success" &amp;&amp; output2[0].result === "success") { var single_blog = output.data[0].single_blog; var blog_comment = output2.data[0].blog_comment; $(".blog").empty().append(single_blog); console.log(blog_comment); } }) .fail(function() { console.log("error"); }) </code></pre>
27,191,941
0
regular expression for all characters not in this range AND another character <p>I need to strip all characters that are not part of the ASCII standard EXCEPT FROM one other character.</p> <p>In order to find all the non-ASCII character I use this regex:</p> <pre><code>/[^\x01-\x7F]/ </code></pre> <p>In order to exclude the character \x92 as well, how must I rewrite the regex?</p> <p>Thanks.</p>
24,633,248
0
<p>The Firebug Working Group is working on fixing this problem in <a href="https://code.google.com/p/fbug/issues/detail?id=7301" rel="nofollow">issue 7301</a>. The issue is currently missing a reproducible test case. So any tips that help to fix this problem or a simple test case should be posted there.</p> <p>You and nmaier already named the workarounds known so far, which are Firebug menu > <em>Options</em> > <em>Reset All Firebug Options</em> or deleting the breakpoints.json file manually from the profile folder followed by a browser restart.</p>
25,817,181
0
Points behind lines in gnuplot <p>I was trying to make a graph of the two minimums of a function, however I ran into some trouble<br> <img src="https://i.stack.imgur.com/upC4o.png" alt="a plot"></p> <pre><code>set terminal pngcairo set output "plot.png" f(x) = x**4-25*x**2+20*x set xrange [-6:6] set yrange [-300:600] set label 1 "" at -3.7207,f(-3.7207) point pt 7 lt 1 set label 2 "" at 3.3154,f(3.3154) point pt 7 lt 2 plot f(x) title "x^4+25x^2+20x" </code></pre> <p>As you can see on the green point, it's behind the curve, I would like to make it so the green point is in front.</p> <p>I found a workaround by using multiplot to plot the points after the curve, but it seems absurd to me that you have to use this workaround.</p> <p><img src="https://i.stack.imgur.com/CNS83.png" alt="another plot"></p> <pre><code>set terminal pngcairo set output "plot1.png" f(x) = x**4-25*x**2+20*x set multiplot set xrange [-6:6] set yrange [-300:600] plot f(x) title "x^4+25x^2+20x" set label 1 "" at -3.7207,f(-3.7207) point pt 7 lt 1 set label 2 "" at 3.3154,f(3.3154) point pt 7 lt 2 plot NaN notitle </code></pre>
8,987,382
0
<blockquote> <p>should I create an unit test for a string formatting that's supossed to be user-input? Or is it just wasting my time while I just can check it in the actual code?</p> </blockquote> <p>Not sure I understand what you mean, but the tests you write in TDD are supposed to test your production code. They aren't tests that check user input.</p> <p>To put it another way, there can be TDD unit tests that test the user input validation <em>code</em>, but there can't be TDD unit tests that validate the user input itself.</p>
18,051,732
0
<p>Try</p> <pre><code>&lt;li class="nav-item" data-location="content.htm"&gt;About Us&lt;/li&gt; &lt;li class="nav-item" data-location="actsAndRules.htm"&gt;Rules&lt;/li&gt; </code></pre> <p>Then </p> <pre><code>$(function(){ $('.nav-item').click(function(){ if(!$elesToHide.is(":visible")){ $elesToHide.slideDown(); } $c.load($this.data('location') ) ; }) }) </code></pre>
1,830,160
0
<p>The following How To from the Xamarin.iOS guide site has a few pointers to where to store your files:</p> <p><a href="http://docs.xamarin.com/guides/ios/application_fundamentals/working_with_the_file_system/" rel="nofollow noreferrer">http://docs.xamarin.com/guides/ios/application_fundamentals/working_with_the_file_system/</a></p>
8,904,583
0
<p>I imagine the reason it's not working is because the context in which it'll look for your function will be the top one, i.e. the window.</p> <p>What you'll need to do is rename the function <code>window.subscribe_callback = (data)-&gt;</code> etc instead.</p>
40,549,714
0
<p>Depending on your XSLT processor you might first want to check whether there is support the the XPath 3.0 <code>serialize</code> function <a href="https://www.w3.org/TR/xpath-functions-30/#func-serialize" rel="nofollow noreferrer">https://www.w3.org/TR/xpath-functions-30/#func-serialize</a> or a built-in extension function to do the job.</p> <p>If you want to perform it with XSLT then, in your template, you need to process the attributes as well, e.g. </p> <pre><code>&lt;xsl:template match="*" mode="serialize"&gt; &lt;xsl:text&gt;&amp;lt;&lt;/xsl:text&gt; &lt;xsl:value-of select="name()"/&gt; &lt;xsl:apply-templates select="@*" mode="serialize"/&gt; ... &lt;/xsl:template&gt; </code></pre> <p>Be aware that worked out solutions like <a href="http://lenzconsulting.com/xml-to-string/" rel="nofollow noreferrer">http://lenzconsulting.com/xml-to-string/</a> exist and are probably better then a quick attempt with some templates as a proper serialization which really produces namespace well-formed XML that round-trips is quite a challenge. </p>
20,152,310
0
How to capture ring back tone (RBT) sound and record it in java android? <p>I hope to find answer here, I want to get the calling parties ring tone, I mean when you call somebody, before your call is established with that person, you may here some music instead of default beep sound, actually that person may have activated RBT or RING BACK TONE (from aT&amp;T maybe) on her mobile number. How I can capture her ring back tone sound stream and convert it to array of byte[]? I need to capture that RBT? thanks all,</p>
22,762,164
0
<p><code>final_3root</code> is missing a return statement. </p> <p>Look closely at the error. <code>x</code> is <code>None</code>. If you trace it back, you'll see that the return value of that function is used, but it never returns anything. </p>
19,892,258
0
jquery tablesorter - formatted currency - what do I do wrong? <p>I had problems handling currencies, then I used this code</p> <pre><code>&lt;script type='text/javascript'&gt; $(document).ready(function () { $(&amp;quot;#3dprojector&amp;quot;).tablesorter(); } ); // add parser through the tablesorter addParser method $.tablesorter.addParser({ // set a unique id id: 'thousands', is: function(s) { // return false so this parser is not auto detected return false; }, format: function(s) { // format your data for normalization return s.replace('$','').replace(/,/g,''); }, // set type, either numeric or text type: 'numeric' }); $(function() { $("table").tablesorter({ headers: { 1: {//zero-based column index sorter:'thousands' } } }); }); &lt;/script&gt; </code></pre> <p>the problem is, it only sorts only one way. I'm not sure if I have used parser the right way. This script is before finishing /head tag on my website. Thanks for help :-)</p>
26,196,644
0
Clojure newbie struggling with protocols <p>I am attempting to build out the <a href="https://github.com/dustingetz/react-cursor" rel="nofollow">concept of a Cursor</a> in clojurescript, backed by an atom. A cursor is a recursive zipper like mechanism for editing an immutable nested associated datastructure.</p> <p>I am very newbie at Clojure, can you help me spot my errors?</p> <pre><code>(defprotocol Cursor (refine [this path]) (set [this value]) (value [this])) (defn- build-cursor* [state-atom paths] (reify Cursor (set [this value] (swap! state-atom (assoc-in @state-atom paths value))) (refine [this path] (build-cursor* state-atom (conj paths path))) (value [this] (get-in @state-atom paths)))) (defn build-cursor [state-atom] (build-cursor* state-atom [])) (comment (def s (atom {:a 42})) (def c (build-cursor s)) (assert (= (value c) {:a 42})) (set c {:a 43}) ;; WARNING: Wrong number of args (2) passed to quiescent-json-editor.core/set at line 1 &lt;cljs repl&gt; (assert (= (value c) {:a 43})) (def ca (refine c :a)) ;; WARNING: Wrong number of args (2) passed to quiescent-json-editor.core/refine at line 1 &lt;cljs repl&gt; (assert (= (value ca) 43)) (set ca 44) (assert (= (value ca) 43)) ) </code></pre>
30,567,208
0
C# How to Determine if Netwokr Path Exists w/o new Process <p>I want to check if a certain network drive is accessible and exit my addin if not. It's an Outlook 2013 addin in VSTO. Anyway, I would like to search for it by UNC if possible as \192.168.0.2\WAN\ or I could use the drive letter as a last last resort, but not everyone uses the same letter for that drive in our company. </p> <p>Anyway if I do <code>Directory.Exists("path with correct drive letter");</code> it hangs. I want to just see if its there or not. </p> <p>Can someone provide assistance and also give me a small example?</p> <p>Oh and by the way, there is an answer where a process is spawned to do net use. I wanted to do it without spawning a new process wanted to know if it was possible.</p> <p>Thanks a ton</p>
13,732,876
0
<p>This one works for me ;-)</p> <pre><code>if (pref instanceof RingtonePreference) { Log.i("***", "RingtonePreference " + pref.getKey()); final RingtonePreference ringPref = (RingtonePreference) pref; ringPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Log.i("***", "Changed " + newValue.toString()); Ringtone ringtone = RingtoneManager.getRingtone( SettingsActivity.this, Uri.parse((String) newValue)); ringPref.setSummary(ringtone.getTitle(SettingsActivity.this)); return true; } }); String ringtonePath=pref.getSharedPreferences().getString(pref.getKey(), "defValue"); Ringtone ringtone = RingtoneManager.getRingtone( SettingsActivity.this, Uri.parse((String) ringtonePath)); ringPref.setSummary(ringtone.getTitle(SettingsActivity.this)); } </code></pre>
37,668,337
0
<p>Make sure that you check all bin folders. I mean it can be changed in bin folder, but reference in project can be still to 4.0.0.0.</p>
27,963,654
0
<p>The display issue is caused by the Editor that outputs the iframe with size "width: 0px". </p> <p>Next step, finding a possible <strong>solution</strong>:</p> <p><strong>CSS</strong> Set a predefined width for all Iframes, example [CSS][1];</p> <p>OR</p> <p><strong>Jquery</strong> (Example: [change-iframe-width-and-height-using-jquery][2])</p> <pre><code>[1]: http://jsfiddle.net/7WRHM/1001/ [2]: http://stackoverflow.com/a/14913861/2842657 </code></pre> <p><strong><em>I have not tested thoroughly but this solution seems to solve the issue</em></strong>: </p> <pre><code>.cke_contents &gt; iframe{ width: 100% !important; } </code></pre>
23,777,013
0
<p>This would be very easy with the PHP SDK. A <code>signed_request</code> parameter will get passed on to your iframe, and the PHP SDK offers a function called <code>getSignedRequest()</code> to parse it:</p> <p><a href="https://developers.facebook.com/docs/reference/php/facebook-getSignedRequest/" rel="nofollow">https://developers.facebook.com/docs/reference/php/facebook-getSignedRequest/</a></p> <p>For example:</p> <pre><code>$sr = $fb-&gt;getSignedRequest(); echo $sr['page']['id']; </code></pre> <p>With JavaScript it would be a lot more complicated. You could try to get the signed_request parameter like this: <a href="http://stackoverflow.com/questions/5448545/how-to-retrieve-get-parameters-from-javascript">How to retrieve GET parameters from javascript?</a> - But you would have to deal with the parameter on your own. Here´s how to parse the parameter on your own with PHP: <a href="https://developers.facebook.com/docs/facebook-login/using-login-with-games" rel="nofollow">https://developers.facebook.com/docs/facebook-login/using-login-with-games</a></p> <p>No Facebook SDK needed in that case, btw. And it should also work with PHP &lt;5.4.</p>
40,632,194
0
<p>Within the standard language, the approach was typically to set aside storage in an array that was larger than likely needed, but still within the constraints of the platform running the program, then manually parcel that storage out as required. The language had features, such as sequence association, storage association, and adjustable arrays, that helped with this parcelling.</p> <p>Use of language extensions for dynamic memory management was also common.</p> <p>The capabilities of Fortran 77 and earlier need to be considered in the context of the capabilities of the platforms of the time.</p>
28,431,049
0
Converting DXL timestamp to C# DateTime <p>totally messed up with Lotus Notes DXL timestamp format... Given is a timestamp of an exported DXL from a Lotus Notes document, which looks like that:</p> <pre><code>20141104T132939,49+01 </code></pre> <p>Trying to get the format working with <code>DateTime.ParseExact</code>, like:</p> <pre><code>DateTime.ParseExact(dateStr.Substring(0, 13), "yyyyMMddThhmm", System.Globalization.CultureInfo.InvariantCulture).ToString("dd.MM.yyyy hh:mm"); </code></pre> <p>But with no luck >>> <code>System.FormatException "no valid DateTime format"</code>.</p> <p>Can C# handle the above timestamp as it is?</p>
4,555,057
0
UML and java classes <p>I do need your valuable help. A few weeks ago I developed a small program in Java. Probably a wrong approach, but I didn't tackle the problem with UML in mind, but on the basis of a given idea I built a fully functional piece of software which lives up to expectations.</p> <p>The program itself consist of two classes and several methods.</p> <p>Now I need to draw the corresponding UML class diagram and it seems a very knotty problem for me.</p> <p>Since the UML class diagram aims at showing the source code dependencies between classes, I'm wondering how I can draw a class diagram based on the following code.</p> <p>.................................................................</p> <p>import javax.swing.JPanel; class WavPanel extends JPanel {</p> <pre><code> List&lt;Byte&gt; audioBytes; List&lt;Line2D.Double&gt; lines; public WavPanel() { super(); setBackground(Color.black); resetWaveform(); } public void resetWaveform() { audioBytes = new ArrayList&lt;Byte&gt;(); lines = new ArrayList&lt;Line2D.Double&gt;(); repaint(); } } </code></pre> <p>................................................................</p> <p>In a nutshell, the WavPanel class is an example of inheritance. The JPanel class (part of a package) acts as a superclass. How can I solve the problem? My concern is that JPanel is a class which is part of a package.</p> <p>Furthermore, in order to draw a good class diagram am I wrong in thinking that maybe I had to do the UML diagram first and then write the associated code?</p> <p>The fact that I wrote several methods (instead of classes) and just a few classes, can that be a problem with UML? If so it would mean reengineering the entire software again.</p> <p>Thanks in advance . Any help will be highly appreciated.</p>
19,188,169
0
<p>I would suggest you this approach:</p> <ul> <li>Split <code>userInput</code> string by white spaces: <code>userInput.split("\\s+")</code>. You will get an array. See <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29" rel="nofollow">String.split()</a></li> <li>For question 1: iterate over the array comparing each string with your <em>keyword</em>. See <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals%28java.lang.Object%29" rel="nofollow">String.equals()</a> and <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equalsIgnoreCase%28java.lang.String%29" rel="nofollow">String.equalsIgnoreCase()</a>.</li> <li>For question 2: add the array to a <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Set.html" rel="nofollow">Set</a>. As this can't contain any duplicate item, its size will give you the answer.</li> </ul>
40,092,664
0
<p>If nothing works, try replacing the contents of your file with the content of any other valid testng.xml file. This worked in my case.</p>
17,060,285
0
Java: double: how to ALWAYS show two decimal digits <p>I use double values in my project and i would like to always show the first two decimal digits, even if them are zeros. I use this function for rounding and if the value I print is 3.47233322 it (correctly) prints 3.47. But when i print, for example, the value 2 it prints 2.0 .</p> <pre><code>public static double round(double d) { BigDecimal bd = new BigDecimal(d); bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP); return bd.doubleValue(); } </code></pre> <p>I want to print 2.00! </p> <p>Is there a way to do this without using Strings? </p> <p>Thanks!</p> <p>EDIT: from your answers (wich I thank you for) I understand that I wasn't clear in telling what I am searching (and I'm sorry for this): I know how to print two digits after the number using the solutions you proposed... what i want is to store in the double value directly the two digits! So that when I do something like this <code>System.out.println("" + d)</code> (where d is my double with value 2) it prints 2.00. </p> <p>I'm starting to think that there is no way to do this... right? Thank you again anyway for your answers, please let me know if you know a solution!</p>
25,965,636
0
MySQL count a number of entries within time period sharing at least 1 of 3 columns <p>I have a table that logs invalid user login attempts. Every time an invalid attempt is made, the username, user IP, user email and time/date is stored in the database.</p> <p>What I'd like to do is check if within ANY 24 hour time period there has been more than X invalid attempts by the same user. However, the users can change the email, username or IP at any point. So, I need to check that anyone of these 3 fields is in common.</p> <p>For example:</p> <ul> <li>User ID: 1; IP: 1.1.1.1; Email: test@test.com </li> <li>User ID: 2; IP: 1.1.1.1; Email: test2@test.com </li> <li>User ID: 1; IP: 1.1.1.2; Email: test3@test.com</li> <li>User ID: 4; IP: 1.1.1.4; Email: test@test.com</li> <li>User ID: 5; IP: 1.1.1.4; Email: test5@test.com</li> </ul> <p>All of these would match as the SAME user because they share EITHER the user ID, the IP or the email. Then I need to output all user IDs, IPs and emails so I can ban any user in another table that matches these criteria. </p>
25,879,057
0
<p>You say you're outputting a csv. Are you sure your data fields have no commas in them? That can manifest as "extra" columns when you read the csv file. Or does your "NAME" field have single-quotes and commas in it that might break your explicit double-quoting?</p> <p>Look at the records with "extra" fields in them &amp; trace back to your source data. The first spurious value will tell you where the breakage is.</p>
22,609,877
0
<p>the controls have an opacity when moving which by default is set to 0.4. To prevent that you can do this: </p> <pre><code>canvas.item(0).set({ borderOpacityWhenMoving: 1 }); </code></pre> <p>As far as I know the control knobs cannot be changed. You'd have to change the function that actually draws the controls. This is done in the function drawControls which either uses strokeRect or fillRect depending on the settings to draw the controls. You should be able to change the function to draw a circle.</p> <p>hope this helps. </p>
18,915,280
0
Consequences of including an external script file in a GTM tag <p>In GTM, lets say that I have a "custom HTML" tag, and in it include an external script file like </p> <p><code>&lt;script type="text/javascript" src="http://externalsite.com/file.js"&gt;&lt;/script&gt;</code></p> <p>How is this file loaded? Does it affect the loading time of the page?</p> <p>I know that the GTM script is loaded asynchronously along with the tags, but I can't really imagine what happens in this case.</p>
20,192,471
0
<p>According to me you have to clear each activity from stack using</p> <pre><code> youractivityname.this.finish(); </code></pre>
2,028,626
0
<p>No, an iPhone application can only change stuff within its own little sandbox. (And even there there are things that you can't change on the fly.)</p> <p>Your best bet is probably to use the servers IP address rather than hostname. Slightly harder, but not <em>that</em> hard if you just need to resolve a single address, would be to put a DNS server on your Mac and configure your iPhone to use that.</p>
37,551,807
1
How to send multiple messages to eventhub using python <p>I already send batch messages using C# libs. I want to do the same thing using python, how to do it? Actually I'm able to send single messages but batch send will increase my throughtput. This is the code:</p> <pre><code>from azure.servicebus import ServiceBusService key_name = 'RootManageSharedAccessKey' # SharedAccessKeyName from Azure portal key_value = '' # SharedAccessKey from Azure portal sbs = ServiceBusService(service_namespace, shared_access_key_name=key_name, shared_access_key_value=key_value) sbs.send_event('myhub', '{ "DeviceId":"dev-01", "Temperature":"37.0" }') </code></pre> <p>I think it's possible because on the manual it says:</p> <p>"The event content is the event message or JSON-encoded string that contains multiple messages."</p> <p><a href="http://azure-sdk-for-python.readthedocs.io/en/latest/servicebus.html?highlight=event%20hub" rel="nofollow">Link to the manual</a></p>
7,780,691
0
<p>this.x and this.y are functional from the scope of your checkers pieces object; however, if you're accessing a piece outside of their scope, you must use a piece's instance name. Although not optimal, you could loop through children DisplayObjects.</p> <pre><code>// create a collection of your checker pieces var checkers:Array = []; // create a checker piece, whatever your DisplayObject class is. var checker:Checker; checkers.push(checker); // add it to the stage, probably your game board addChild(checker); checker.x = 100; checker.y = 100; // loop through the children (from your game board) for (var i:uint = 0; i &lt; numChildren; i++) { var checker:DisplayObject = getChildAt(i); trace(checker.x); trace(checker.y); } </code></pre> <p>Using coordinates to reference a piece may not be optimal for game play. You might want to consider a row / column or approach it from how your game board works.</p> <p>If this is not clear, you should specify some code or expand your question with more detail.</p>
3,188,853
0
Launching Android Native Lock Screen <p>I'm looking for a way to launch the native android lock screen from my application. I've looked around and found code about KeyGuardLock and KeyGuardManager but I believe that only locks the keyboard from working.</p> <p>REF: <a href="http://smartandroidians.blogspot.com/2010/03/enabling-and-disabling-lock-screen-in.html" rel="nofollow noreferrer">http://smartandroidians.blogspot.com/2010/03/enabling-and-disabling-lock-screen-in.html</a></p>
11,671,990
0
<p>@Esailija is correct; return HTTP status codes so that jQuery's ajax error handler can receive the error.</p>
21,801,162
0
Cakephp - joining tables, NOT in <p>I'm a newbie and I'm trying to make a Query but don't get it how to do the Query in cake-style. I want to do a query that Selects all respondents thats not in a particular transformational. Examples at the bottom. Cakephp v 2.4.5</p> <p>I have to three tables/models:</p> <p>Resondents: id, name</p> <pre><code>public $hasAndBelongsToMany = array( 'Transformational' =&gt; array( 'className' =&gt; 'Transformational', 'joinTable' =&gt; 'transformationals_respondents', 'foreignKey' =&gt; 'respondent_id', 'associationForeignKey' =&gt; 'transformational_id', 'unique' =&gt; true ) ); </code></pre> <p>Transformationals: id, name</p> <pre><code> public $hasAndBelongsToMany = array( 'Respondent' =&gt; array( 'className' =&gt; 'Respondent', 'joinTable' =&gt; 'transformationals_respondents', 'foreignKey' =&gt; 'transformational_id', 'associationForeignKey' =&gt; 'respondent_id', 'unique' =&gt; true ), }; </code></pre> <p>TransformationasRespondent: id, transformational_id, respondent_id This is a join table</p> <p>Example tables: respondent: id, name 1, Abc 2, Def 3, Ghi 4, Jkl</p> <p>transformationals: id, name 1, Macrosoft 2, Eddy 3, Wag</p> <p>transformationals_respondents: id, respondent_id, transformational_id 1, 1, 7 2, 2, 7</p> <p>THen I need Query to SELECT respondents thats NOT in transformationals_respondents and has transformational_id 7. Ie. respondent Ghi and Jkl</p> <p>I would really appreciate a hand here.</p>
11,385,801
0
Sort by Double Value and not String Value <p>I'm currently pulling info from an sql DB where the 'cachedDist' column is set as a double. However when I pull it into my app and create my array I turn it into an String and the sort will obviously be off, 18.15 will come before 2.15. How do I fix that in my code so it will sort distance as a Double and not a String?</p> <p>In Bar object.</p> <pre><code>NSString *cachedDist @property(nonatomic,copy) NSString *cachedDist; </code></pre> <hr> <pre><code>@synthesize cachedDist; </code></pre> <hr> <p>My while loop in the View Controller.</p> <pre><code>while (sqlite3_step(sqlStatement)==SQLITE_ROW) { Bar * bar = [[Bar alloc] init]; bar.barName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)]; bar.barAddress = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)]; bar.barCity = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 3)]; bar.barState = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 4)]; bar.barZip = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 5)]; bar.barLat = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 8)]; bar.barLong = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 9)]; if (currentLoc == nil) { NSLog(@"current location is nil %@", currentLoc); }else{ CLLocation *barLocation = [[CLLocation alloc] initWithLatitude:[bar.barLat doubleValue] longitude:[bar.barLong doubleValue]]; bar.cachedDist = [NSNumber numberWithDouble:[currentLoc distanceFromLocation: barLocation]/1000]; [thebars addObject:bar]; } </code></pre> <p>My sorting</p> <pre><code>NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"cachedDist" ascending:YES]; sortedArray = [thebars sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]]; return sortedArray; </code></pre>
33,310,701
0
Merging cells with VBA <p>I'm looking to merge 3 horizontal cells, but i am doing so in a loop. The code looks something like this: </p> <pre><code>myrange.Range(cells(3,i), cells(3,i+3)).mergecells = true </code></pre> <p>This is not working. I'm guessing its because the code is trying to merge 2 cells that are not adjacent to each other. What is the syntax for merging a range of cells using this cell-address type?</p> <p>Any help would be greatly appreciated! thanks! </p>
11,263,964
0
<p><a href="http://www.stunnel.org/" rel="nofollow">Stunnel</a> does almost exactly what you ask if the following conditions are met.</p> <ul> <li>One stunnel instance must be running for each service (either from inetd or in standalone daemon-like mode).</li> <li>The system running cURL must manually resolve the hostname of the target service to the IP address of the host running stunnel (e.g. <code>/etc/hosts</code>) in order to use it.</li> </ul> <p>I used stunnel in a similar way for connecting to IRC servers using SSL with SSL-capable clients. It works like a charm, one important thing to be careful about is the incompatibilities between the 3.x and newer versions. If you're planning for a new system, you should probably use the new ones.</p>
27,003,353
0
C# simple code to write an INSERT query is giving an exception <p>I have a very basic and beginner problem. I got a 5 line code and I got exception in that.</p> <p>My database : <img src="https://i.imgur.com/Tgp35mL.png" alt="Table -&gt; id,name"></p> <p>It has one table and two columns inside the table viz. id and name. I made a form.</p> <p>Here is my code:</p> <pre><code>private void button1_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"C:\\Users\\Nicki\\documents\\visual studio 2012\\Projects\\WindowsFormsApplication2\\WindowsFormsApplication2\\Database2.mdf\";Integrated Security=True"); conn.Open(); SqlCommand command = new SqlCommand("INSERT INTO Table (id,name) VALUES (1,'" + textBox1.Text + "')", conn); command.ExecuteNonQuery(); conn.Close(); } </code></pre> <p>I get the following exception on running the code: <img src="https://i.imgur.com/cmpGuEV.png" alt=""></p> <p>It says that I have syntax error even though the syntax error is correct. Any help would be appreciated.</p> <p>Thankyou!</p>
37,804,485
0
<p>Check below code and comment:</p> <pre><code>import java.util.Arrays; public class SortString { public static void main(String[] args) { String str = "11,22,13,31,21,12"; StringBuffer strB = new StringBuffer(); String[] arr = str.split(","); // Split string save in array Arrays.sort(arr); // sort array for (int i = 0; i &lt; arr.length; i++) { //add array in stringbuffer if (i != arr.length - 1) { strB.append(arr[i] + ","); } else { strB.append(arr[i]); } } String str2 = strB.toString(); System.out.println(str2); } } </code></pre>
16,806,021
0
Friends and nested classes <p>Ok I'm totally frazzled on this. Code is begin to swim around the screen...must sleep.</p> <p>So! Ok, troubled by nested classes and friends.</p> <p>here is the pseudo-code</p> <pre><code> class A{ public: //constructor // member functions private: class B{ //private int a(); }; class C{ //private int b(); }; }; </code></pre> <p>So once an object of type A has been created, I would like it to access a() and b(). I know that I have to use a friend function for this. So where should I put friend class A. Is that the right expression?.</p>
6,015,196
0
Method to change self-closing tags to explicit tags in Javascript? <p>Does there exist a method or function that can convert the self-closing tags to explicit tags in Javascript? For example:</p> <pre><code>&lt;span class="label"/&gt; </code></pre> <p>converted to :</p> <pre><code>&lt;span class ="label"&gt;&lt;/span&gt; </code></pre> <hr> <p>I would like to copy a new HTML from the iframe to the outerHTML of the main page, as the new HTML generated contains self-closing tags, the outerHTML doesn't recognize them and then doesn't change and the page doesn't show correctly. But when the format is standard, that is,with the non-self-closing tags, the outerHTML will take the new HTML,and the page shows perfectly.This is why I would like to change the tags.</p> <hr> <h2>And this html is in a string</h2> <p>In fact, I don't want to parse HTML, I just want to find the "&lt; span.../>"and replace it with "&lt; span...>&lt; /span>"</p>
9,645,746
0
<p>Facebook style video embed plugin for jQuery <a href="http://ajaxdump.com/2011/04/26/facebook-style-video-embed-plugin-for-jquery/" rel="nofollow">http://ajaxdump.com/2011/04/26/facebook-style-video-embed-plugin-for-jquery/</a></p>
10,714,707
0
<p>Your approach is ok, but you can make something more generic, like storing the config data for Redis in a file or passing the host and port like arguments:</p> <p><code>node app.js REDIS_HOST REDIS_PORT</code></p> <p>Then in your app you can grab them using process.argv:</p> <pre><code>app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); var r = require("redis").createClient(process.argv[2], process.argv[3]); }); app.configure('production', function(){ app.use(express.errorHandler()); var r = require("redis").createClient(process.argv[2], process.argv[3], { detect_buffers: true }); }); </code></pre> <p>Update:</p> <p>Express will know in what environment you're in by looking at the NODE_ENV variable (process.env.NODE_ENV): <a href="https://github.com/visionmedia/express/blob/master/lib/application.js#L55">https://github.com/visionmedia/express/blob/master/lib/application.js#L55</a></p> <p>You can set that variable when starting the app like so: <code>NODE_ENV=production node app.js</code> (recommended), setting process.env.NODE_ENV manually in your node app before the Express code or putting that env var in ~/.profile like Ricardo said.</p>
16,019,599
0
<p>@Saurabh Nanda: Similar to what you posted, you can also create a simple function to convert your varchar array to lowercase as follows:</p> <pre><code>CREATE OR REPLACE FUNCTION array_lowercase(varchar[]) RETURNS varchar[] AS $BODY$ SELECT array_agg(q.tag) FROM ( SELECT btrim(lower(unnest($1)))::varchar AS tag ) AS q; $BODY$ language sql IMMUTABLE; </code></pre> <p>Note that I'm also trimming the tags of spaces. This might not be necessary for you but I usually do for consistency.</p> <p>Testing:</p> <pre><code>SELECT array_lowercase(array['Hello','WOrLD']); array_lowercase ----------------- {hello,world} (1 row) </code></pre> <p>As noted by Saurabh, you can then create a GIN index:</p> <pre><code>CREATE INDEX ix_tags ON tagtable USING GIN(array_lowercase(tags)); </code></pre> <p>And query:</p> <pre><code>SELECT * FROM tagtable WHERE ARRAY['mytag'::varchar] &amp;&amp; array_lowercase(tags); </code></pre> <p><strong>UPDATE:</strong> Performance of <code>WHILE</code> vs array_agg/unnest</p> <p>I created table of 100K 10 element <code>text[]</code> arrays (12 character random mixed case strings) and tested each function.</p> <p>The array_agg/unnest function returned:</p> <pre><code>EXPLAIN ANALYZE VERBOSE SELECT array_lowercase(data) FROM test; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------ Seq Scan on public.test (cost=0.00..28703.00 rows=100000 width=184) (actual time=0.320..3041.292 rows=100000 loops=1) Output: array_lowercase((data)::character varying[]) Total runtime: 3174.690 ms (3 rows) </code></pre> <p>The WHILE function returned:</p> <pre><code>EXPLAIN ANALYZE VERBOSE SELECT array_lowercase_while(data) FROM test; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------ Seq Scan on public.test (cost=0.00..28703.00 rows=100000 width=184) (actual time=5.128..4356.647 rows=100000 loops=1) Output: array_lowercase_while((data)::character varying[]) Total runtime: 4485.226 ms (3 rows) </code></pre> <p><strong>UPDATE 2:</strong> <code>FOREACH</code> vs. <code>WHILE</code> As a final experiment, I changed the WHILE function to use FOREACH:</p> <pre><code>CREATE OR REPLACE FUNCTION array_lowercase_foreach(p_input varchar[]) RETURNS varchar[] AS $BODY$ DECLARE el text; r varchar[]; BEGIN FOREACH el IN ARRAY p_input LOOP r := r || btrim(lower(el))::varchar; END LOOP; RETURN r; END; $BODY$ language 'plpgsql' </code></pre> <p>Results appeared to be similar to <code>WHILE</code>:</p> <pre><code>EXPLAIN ANALYZE VERBOSE SELECT array_lowercase_foreach(data) FROM test; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------ Seq Scan on public.test (cost=0.00..28703.00 rows=100000 width=184) (actual time=0.707..4106.867 rows=100000 loops=1) Output: array_lowercase_foreach((data)::character varying[]) Total runtime: 4239.958 ms (3 rows) </code></pre> <p>Though my tests are not by any means rigorous, I did run each version a number of times and found the numbers to be representative, suggesting that the SQL method (array_agg/unnest) is the fastest.</p>
1,751,540
0
specifying column names of a data frame within a function ahead of time <p>Suppose you're trying to create a data frame within a function. I would like to be able to define the column names ahead of time as one of the parameters of the function. Take the following code:</p> <pre><code> foo &lt;- function(a) { answer &lt;- data.frame(a=1:5) return(answer) } </code></pre> <p>In the above example, I would like to be able to specify the value of the column name in the function <code>foo()</code>, e.g. <code>foo('my.name')</code> so that answer has the column name <code>my.name</code> instead of <code>a</code>. I imagine you could code this up within the function using <code>colnames()</code>, but I was interested in an alternative approach.</p>
6,981,179
0
ComboBox not binding in datagrid <p>I have a ComboBox binded to BindingList with strings. It is working fine.</p> <pre><code>public BindingList&lt;string&gt; MyList { get { BindingList&lt;string&gt; list = new BindingList&lt;string&gt;(); list.Add("one"); list.Add("two"); list.Add("three"); return list; } } </code></pre> <p>xaml:</p> <pre><code>&lt;ComboBox x:Name="MyCmbBox" ItemsSource="{Binding Path=MyList}"&gt; &lt;ComboBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;TextBlock Text="{Binding}" /&gt; &lt;/DataTemplate&gt; &lt;/ComboBox.ItemTemplate&gt; &lt;/ComboBox&gt; </code></pre> <p>When I same code put into the WPF 4 datagrid, it's not working any more (but the combo outside datagrid is still running ok):</p> <pre><code>&lt;DataGrid AutoGenerateColumns="False"&gt; &lt;DataGrid.Columns&gt; &lt;DataGridTemplateColumn&gt; &lt;DataGridTemplateColumn.CellTemplate&gt; &lt;DataTemplate&gt; &lt;ComboBox x:Name="MyCmbBox" ItemsSource="{Binding Path=MyList}"&gt; &lt;ComboBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;TextBlock Text="{Binding}" /&gt; &lt;/DataTemplate&gt; &lt;/ComboBox.ItemTemplate&gt; &lt;/ComboBox&gt; &lt;/DataTemplate&gt; &lt;/DataGridTemplateColumn.CellTemplate&gt; &lt;/DataGridTemplateColumn&gt; &lt;/DataGrid.Columns&gt; &lt;/DataGrid&gt; </code></pre> <p>Why? Thank you</p>
37,144,408
0
<p>Using maths function Logarithm should do the trick, as your speed will reach a limit and distance will also use the same path, the effect will be smoothier.</p>
7,560,858
0
problem displaying webpage on different computers <p>I have a very weird problem.<br> I have a webpage that displays some graphs using Jquery. This page works fine on my laptop &amp; my other colleagues laptop.<br> But there is one particular PC that does not display the webpage properly. I thought that it might be a browser issue but when I connected remotely to that PC from my laptop, the webpage displayed the graphs perfectly.<br> I am not sure if this is an hardware related problem, my laptop's screen size is 15" while the PC that gives problem has a screen size of 40"<br> Please help. </p> <p>Regards, Krum</p>
33,835,975
0
Does provisioning have a place in the Drupal world? <p>My team is relatively new to Drupal. One thing we have struggled to understand is how to work with it from a DevOps point of view. I realize this is too large a subject for one question so I have a more specific question that gets at the heart of the matter.</p> <p>How does one provision a Drupal instance? By "provision", I mean create a provisioning script that builds my CMS (we're only using Drupal for that purpose) starting with a clean virtual machine with only OS and web server. The script would install and configure Drupal and its modules and connect to an existing database containing my content. Or perhaps I can even have it add my content to Drupal instance with an empty database. I'm just not sure what makes sense.</p> <p>What I am trying to avoid is the uncertainty and non-reproducability that comes with doing everything interactively via Drupal's UI. I realize that Drupal has lots of techniques for exporting various things but there doesn't appear to be any coherent overall picture. Every bit of advice is of the form, "If you want to do (some specific thing), this is how you might do it." Or, even worse, "This worked for me." Neither of these things gives me much confidence or, more importantly, gives decent "best practices" advice that tells us what Drupal's designers intended.</p> <p>There are some Drupal "best practices" articles but they don't go much beyond advice such as, "Do a backup before changing anything." I need more useful advice.</p>
25,478,829
0
<p>The problem is that your data coming asynchronously but you try save them synchronously. Step by step:</p> <ol> <li>You define variable trail = [] </li> <li>You return trail variable to controller</li> <li>Server responds with data (but you already return trail)</li> </ol> <p>You can solve this problem by using next code:</p> <pre><code>app.service("dataService", function ($http, $routeParams){ this.getSingleTrail = function (){ var trail = []; return $http.get("http://localhost:8080/DMW-skeleton-1.0/trail/findTrailByTrailId/" + $routeParams.trailId); }}) app.controller("searchTrailsCtrl", function ($scope, dataService ) { $scope.trail; dataService.getSingleTrail().success(function(data){ $scope.trail = data; }); }) </code></pre>
14,363,443
0
<p>Rapheal doesn't have setters for <code>width</code> and <code>height</code> on the Paper object, so calling them is not affecting the DOM, but just setting some properties on the Paper object. </p> <p>Passing in the <code>width</code> and <code>height</code> params in the constructor will affect the SVG tag in the DOM.</p> <p>If you want to change the paper's width and height after constrcution, you can set the style properties of the SVG tag like so:</p> <pre><code>var paper = Raphael(domid); paper.canvas.style.width = '200px'; paper.canvas.style.height = '100px'; </code></pre> <p>As Kevin mentioned, it's probably better to use the <code>setSize</code> method to handle runtime resizing.</p> <p>eg)</p> <p><code>paper.setSize(200,100)</code></p> <p>Hope that helps.</p>
16,388,764
0
How to disable function executing in bind method? <p>I've three simple functions</p> <pre><code>var loadPoints = function(successCallback, errorCallback) { $.ajax({ method: 'get', url: '/admin/graph/get-points', dataType: 'json', success: successCallback, error: errorCallback }); } var successLoadPoints = function(points){ console.log('load ok'); //console.log(points); // $.each(points,function(i, item){ // console.log(points[i]); // // }); } var errorLoadPoints = function () { console.log('error with loading points'); } </code></pre> <p>I bind function loadPoints to click event on button</p> <pre><code>$("button#viewPoints").bind( 'click', loadPoints(successLoadPoints,errorLoadPoints) ); </code></pre> <p>But function loadPoints is been executed without click event. Why? How to resolve this problem ?</p>