pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
34,803,357
0
<p>For every touch, you just need create and add(you missed this step) square in touch begin (or touch end), don't do in touch move.</p> <pre><code> override func touchesBegan(touches: Set&lt;UITouch&gt;, withEvent event: UIEvent?) { let touch = touches.first location = touch!.locationInView(self.view) person.center = location for _ in touches { let mySquare: UIView = UIView(frame: CGRect(x: 0,y: 0,width: 20,height: 20)) mySquare.backgroundColor = UIColor.cyanColor() mySquare.center = randomPoint view.addSubview(mySquare) // add square to the view } } </code></pre>
26,937,596
0
<p><strong>Use Ajax for this :</strong></p> <p>Add this code to main page where you want to display table data</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script&gt; function dashboard() { var query_parameter = document.getElementById("name").value; var dataString = 'parameter=' + query_parameter; // AJAX code to execute query and get back to same page with table content without reloading the page. $.ajax({ type: "POST", url: "execute_query.php", data: dataString, cache: false, success: function(html) { // alert(dataString); document.getElementById("table_content").innerHTML=html; } }); return false; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="table_content"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>In <strong>table_content</strong> div the data come from <strong>execute_query.php</strong> page will load without refreshing the page.</p> <p><strong>execute_query.php</strong></p> <pre><code>$user_name = $_POST['parameter']; $query="SELECT * from info where name=$user_name"; $result=mysql_query($query); $rs = mysql_fetch_array($result); do { ?&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $rs['city']; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $rs['phone_number']; ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;?php }while($rs = mysql_fetch_array($result)); </code></pre>
6,359,127
0
<p>Can't you just create a hash map that has a string key and store whatever numeric value you want? I.e. </p> <pre><code>Map&lt;String, Integer&gt; m = new HashMap&lt;String,Integer&gt;(); m.put(makeKey(3,2), 2); // where makeKey returns something like "[3,2]" </code></pre> <p>EDIT: </p> <p>The downside is you don't have a reliable iteration order, i.e. if you want to iterate over everything in the Nth row or column, there's no easy way to do that efficiently.</p>
19,454,923
0
<p>Most people would prevent the form from submitting by calling the <a href="https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault" rel="nofollow"><code>event.preventDefault()</code></a> function. </p> <p>Another means is to remove the onclick attribute of the button, and get the code in <code>processForm()</code> out into <code>.submit(function() {</code> as <code>return false;</code> causes the form to not submit. Also, make the <code>formBlaSubmit()</code> functions return Boolean based on validity, for use in <code>processForm();</code></p> <p><code>katsh</code>'s answer is the same, just easier to digest. </p> <p>(By the way, I'm new to stackoverflow, give me guidance please. )</p>
26,986,591
0
Angularjs: access template in directive <p>What I want to do is to append compiled template to some other DOM element in Angualrjs directive. Is it possible? How? </p> <p>I know you can use transclude to include the template and keep content in the tag, but how do I attach my compiled template to other DOM element?</p> <pre><code>angular.module("my.directive") .directive('passwordStrength', [function(){ return { templateUrl: '/tpl/directive/passwordStrength.html', restrict: 'A', link: function postLink(scope, iElement, iAttrs){ console.log('password strength is running'); iElement.append($template) // problem here!!! } }; }]); </code></pre>
25,883,058
0
<p>Use the option <code>-I/Users/myuser/anaconda/include/python2.7</code> in the <code>gcc</code> command. (That's assuming you are using python 2.7. Change the name to match the version of python that you are using.) You can use the command <code>python-config --cflags</code> to get the full set of recommended compilation flags:</p> <pre><code>$ python-config --cflags -I/Users/myuser/anaconda/include/python2.7 -I/Users/myuser/anaconda/include/python2.7 -fno-strict-aliasing -I/Users/myuser/anaconda/include -arch x86_64 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes </code></pre> <p>However, to build the extension module, I recommend using a simple setup script, such as the following <code>setup.py</code>, and let <code>distutils</code> figure out all the compiling and linking options for you.</p> <pre><code># setup.py from distutils.core import setup, Extension example_module = Extension('_example', sources=['example_wrap.c', 'example.c']) setup(name='example', ext_modules=[example_module], py_modules=["example"]) </code></pre> <p>Then you can run:</p> <pre><code>$ swig -python example.i $ python setup.py build_ext --inplace </code></pre> <p>(Take a look at the compiler commands that are echoed to the terminal when <code>setup.py</code> is run.)</p> <p><code>distutils</code> knows about SWIG, so instead of including <code>example_wrap.c</code> in the list of source files, you can include <code>example.i</code>, and <code>swig</code> will be run automatically by the setup script:</p> <pre><code># setup.py from distutils.core import setup, Extension example_module = Extension('_example', sources=['example.c', 'example.i']) setup(name='example', ext_modules=[example_module], py_modules=["example"]) </code></pre> <p>With the above version of <code>setup.py</code>, you can build the extension module with the single command</p> <pre><code>$ python setup.py build_ext --inplace </code></pre> <p>Once you've built the extension module, you should be able to use it in python:</p> <pre><code>&gt;&gt;&gt; import example &gt;&gt;&gt; example.fact(5) 120 </code></pre> <p>If you'd rather not use the script <code>setup.py</code>, here's a set of commands that worked for me:</p> <pre><code>$ swig -python example.i $ gcc -c -I/Users/myuser/anaconda/include/python2.7 example.c example_wrap.c $ gcc -bundle -undefined dynamic_lookup -L/Users/myuser/anaconda/lib example.o example_wrap.o -o _example.so </code></pre> <p>Note: I'm using Mac OS X 10.9.4:</p> <pre><code>$ gcc --version Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn) Target: x86_64-apple-darwin13.3.0 Thread model: posix </code></pre>
24,585,454
0
How to convert glRotatef() to multiplication matrice for glMultMatrixd() <p>I need to perform some operations with different openGL functions.</p> <p>There for I have a cube initialized as glList. What I'm doing is some transformation with glu standard functions and I like to do exactly the same operations with matrix multiplication. But I got stuck with the rotation function. I want to rotate the cube around the x achsis e.g. 90°:</p> <pre><code>glRotatef(90.0, 1.0f, 0.0f, 0.0f); </code></pre> <p>should be replaced by:</p> <pre><code>GLdouble m[16] ={1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0,-1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }; glMultMatrixd(m); </code></pre> <p>I found <a href="http://www.cs.princeton.edu/~gewang/projects/darth/stuff/quat_faq.html#Q28" rel="nofollow">this very usefull site</a> <strike>but some how it's not doing exactly the same as the above function</strike>. Is there a generell principle how to transform the glRotatef() function to a gl transformation matrix?</p> <p>UPDATE: sorry, I missed the important note a the beginning of the document that the matrices from the document needed to be transposed for use in openGL. </p>
31,756,697
0
<p>I've got no idea how FactoryBoy works, but this strategy usually works for me when I need dynamic properties on fields in Django models:</p> <pre><code>def FooContainerFactory(factory.Factory): def __init__(self, count=20, *args, **kwargs): self.foos = factory.List([Foo() for _ in range(20)]) super(FooContainerFactory, self).__init__(*args, **kwargs) class Meta: model = FooContainerModel </code></pre>
30,694,527
0
Is it safe to pass req as a variable in res.render in expressJs? <p>I'm using NodeJs+ ExpressJs + Handlebars to build a website. When rendering a page I need to pass 3 things everytime : isAuthenticated, userEmail, and FlashMsg. Instead of This :</p> <pre><code>res.render('/webPage', {isAuthenticated: req.isAuthenticated(), userEmail: req.user.email, flashMsg: req.flash()}); </code></pre> <p>Is it safe to do it like that so everythings will be accessible on the page?:</p> <pre><code>res.render('/webPage', {req:req}); </code></pre> <p>Is it too much stuff passed to the page or it's not a problem ? Thanks.</p>
26,230,328
0
<p>Try changing it to this;</p> <pre><code>&lt;% @events.each do |e| %&gt; &lt;%= link_to '&lt;i class=icon-trash&gt;&lt;/i&gt;'.html_safe, account_show_path(@context, @event), :confirm =&gt; 'Are you sure?', :method =&gt; :delete %&gt; &lt;% end %&gt; </code></pre> <p>Make sure you have the following in your header;</p> <pre><code>&lt;%= javascript_include_tag 'application', 'data-turbolinks-track' =&gt; true %&gt; &lt;%= csrf_meta_tags %&gt; </code></pre>
3,243,204
0
WPF Why the assigned background cannot override setter value in style triggers? <p>I have a <code>Style</code> for a <code>TextBox</code> like this:</p> <pre><code>&lt;Style x:Key="TextBox_Standard" TargetType="{x:Type TextBoxBase}" &gt; &lt;Setter Property="Control.FontFamily" Value="/#Calibri" /&gt; &lt;Setter Property="Control.FontSize" Value="12" /&gt; &lt;Setter Property="Control.Margin" Value="2" /&gt; &lt;Setter Property="Control.Height" Value="21" /&gt; &lt;Setter Property="Control.VerticalAlignment" Value="Center" /&gt; &lt;Setter Property="SnapsToDevicePixels" Value="True"/&gt; &lt;Setter Property="UndoLimit" Value="0"/&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type TextBoxBase}"&gt; &lt;Border Name="Border" CornerRadius="1" Padding="1" Background="{StaticResource WindowBackgroundBrush}" BorderBrush="{StaticResource SolidBorderBrush}" BorderThickness="1" &gt; &lt;ScrollViewer Margin="0" x:Name="PART_ContentHost" /&gt; &lt;/Border&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="IsEnabled" Value="False"&gt; &lt;Setter TargetName="Border" Property="Background" Value="{StaticResource DisabledBackgroundBrush}"/&gt; &lt;Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}"/&gt; &lt;Setter Property="Cursor" Value="Arrow"/&gt; &lt;/Trigger&gt; &lt;Trigger Property="IsReadOnly" Value="True"&gt; &lt;Setter TargetName="Border" Property="Background" Value="{StaticResource DisabledBackgroundBrush}"/&gt; &lt;Setter Property="Focusable" Value="False"/&gt; &lt;Setter Property="Cursor" Value="Arrow"/&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre> <p>It was made to make sure the foreground color to be black and background color to be gray when it's not editable.</p> <p>but apparently now there's a requirement to change the background programmatically when it's not editable, so I tried it like this:</p> <p><code>txtBox.Background = Brushes.Yellow;</code></p> <p>but what happens is it still have a white background when editable and gray background when not editable.</p> <p>Where did I go wrong?</p>
19,977,766
0
<p>Looking at your desired output, you are looking for the <code>crossprod</code> function:</p> <pre><code>crossprod(table(test1)) # product # product p1 p2 p3 p4 # p1 4 1 1 0 # p2 1 3 1 0 # p3 1 1 4 1 # p4 0 0 1 2 </code></pre> <p>This is the same as <code>crossprod(table(test1$user, test1$product))</code> (reflecting Dennis's comment).</p>
31,518,924
0
XML to JSON merges tags <p>I am working on a small project and I have encountered an issue for which I cannot find a solution myself or locate something similar on internet. So, I am retrieving information from API in XML format, when I call my own API through JavaScript to retrieve this XML document the data gets converted into JSON format, but the repeating tags get merged into single property. Anyone know how I can stop it ?</p> <p>Here is some Sample data:</p> <pre><code>&lt;then&gt; &lt;test operator="test"&gt; &lt;one&gt; &lt;byte&gt;1&lt;/byte&gt; &lt;/one&gt; &lt;two&gt; &lt;byte&gt;1&lt;/byte&gt; &lt;/two&gt; &lt;/test&gt; &lt;insert&gt; &lt;object&gt; &lt;string&gt;1&lt;/string&gt; &lt;/object&gt; &lt;/insert&gt; &lt;remove&gt; &lt;object&gt;url&lt;/object&gt; &lt;/remove&gt; &lt;test operator="test"&gt; &lt;one&gt; &lt;byte&gt;3&lt;/byte&gt; &lt;/one&gt; &lt;two&gt; &lt;byte&gt;3&lt;/byte&gt; &lt;/two&gt; &lt;/test&gt; &lt;/then&gt; </code></pre> <p>After serialization the output would look like this:</p> <pre><code>{ "then": { "test": [ { "one": { "byte": "1" }, "two": { "byte": "1" }, "_operator": "test" }, { "one": { "byte": "3" }, "two": { "byte": "3" }, "_operator": "test" } ], "insert": { "object": { "string": "1" } }, "remove": { "object": "url" } } } </code></pre> <p>You can see that all test have been merged into 1 property. Is there any way to stop this ?</p>
39,833,233
0
NUnit: Can I use an empty TestCaseSource and still have a test pass? <p>I currently have some unit tests running against all of our controllers and actions, and an additional test for some "temporary exemptions" that we allow (but that receive other checks as a result). </p> <p>We were able to remove all of our temporary exemptions (a good thing), but the functionality needs to remain in place for future use.</p> <p>However, since the <code>TestCaseSource</code> is now empty, NUnit fails the test with "no arguments were provided".</p> <p>I don't necessarily disagree with the behavior, but given my situation, is there any way to ignore the test only when the <code>TestCaseSource</code> is empty, rather than failing with this message?</p>
27,775,846
0
<p>I have solved the issue by changing this line:</p> <pre><code>lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, 200, 200)]; </code></pre> <p>to:</p> <pre><code>lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(0,0, 200, 200)]; </code></pre>
11,592,139
0
MySQL snafoo with GROUP_CONCAT <p>This works:</p> <pre><code>SELECT DISTINCT HEX(group_uuid) AS hexid FROM schema.table &gt;9B3D8DE01E1E049DA9F17D42B324AA66 &gt;CDF112D740CE14EA08CA90E3C937DE8D </code></pre> <p>as does this</p> <pre><code>SELECT GROUP_CONCAT('\'', HEX(group_uuid), '\' ') AS hexid FROM schema.table &gt;'9B3D8DE01E1E049DA9F17D42B324AA66','9B3D8DE01E1E049DA9F17D42B324AA66' [etc...] </code></pre> <p>and this </p> <pre><code>SELECT GROUP_CONCAT(DISTINCT HEX(group_uuid) SEPARATOR '\' ') AS hexid FROM schema.table &gt;9B3D8DE01E1E049DA9F17D42B324AA66' CDF112D740CE14EA08CA90E3C937DE8D </code></pre> <p>this, however,</p> <pre><code>SELECT GROUP_CONCAT('\'', DISTINCT HEX(group_uuid), '\' ') AS hexid FROM schema.table Error Code: 1064. You have an error in your SQL syntax; INSERT COIN </code></pre> <p>does not.</p> <p>Is there some kind 'PREFIX' keyword that can be substituted or another syntax I'm supposed to follow?</p>
22,399,177
0
<p>Get them all at once:</p> <pre><code>Select e1.Employername From Employer e1 Where e1.Salary &gt; (Select avg(e2.Salary) from Employer e2 Where e2.WorkingPosition = e1.WorkingPosition)) </code></pre>
41,067,701
0
<p>If <code>list2</code> is ordered, then simply use your second solution optimized:</p> <pre><code>var exceptIndex = 0; var newList = new List&lt;T&gt;(); for (var i = 0; i &lt; list1.Length; i++) { if (i != list2[exceptIndex]) newList.Add(list1[i]); else exceptIndex++ } return newList; </code></pre>
25,048,112
0
Recaptcha Bug Loop <p>I started to work on recaptcha file but this one keeps looping (don't know why). </p> <pre><code> &lt;?php if (!defined('QA_VERSION')) { // don't allow this page to be requested directly from browser header('Location: ../'); exit; } class qa_recaptcha_captcha { var $directory; function load_module($directory, $urltoroot) { $this-&gt;directory=$directory; } function admin_form() { $saved=false; if (qa_clicked('recaptcha_save_button')) { qa_opt('recaptcha_public_key', qa_post_text('recaptcha_public_key_field')); qa_opt('recaptcha_private_key', qa_post_text('recaptcha_private_key_field')); $saved=true; } $form=array( 'ok' =&gt; $saved ? 'reCAPTCHA settings saved' : null, 'fields' =&gt; array( 'public' =&gt; array( 'label' =&gt; 'reCAPTCHA public key:', 'value' =&gt; qa_opt('recaptcha_public_key'), 'tags' =&gt; 'name="recaptcha_public_key_field"', ), 'private' =&gt; array( 'label' =&gt; 'reCAPTCHA private key:', 'value' =&gt; qa_opt('recaptcha_private_key'), 'tags' =&gt; 'name="recaptcha_private_key_field"', 'error' =&gt; $this-&gt;recaptcha_error_html(), ), ), 'buttons' =&gt; array( array( 'label' =&gt; 'Save Changes', 'tags' =&gt; 'name="recaptcha_save_button"', ), ), ); return $form; } function recaptcha_error_html() { if (!function_exists('fsockopen')) return 'To use reCAPTCHA, the fsockopen() PHP function must be enabled on your server. Please check with your system administrator.'; elseif ( (!strlen(trim(qa_opt('recaptcha_public_key')))) || (!strlen(trim(qa_opt('recaptcha_private_key')))) ) { require_once $this-&gt;directory.'recaptchalib.php'; $url=recaptcha_get_signup_url(@$_SERVER['HTTP_HOST'], qa_opt('site_title')); return 'To use reCAPTCHA, you must &lt;a href="'.qa_html($url).'"&gt;sign up&lt;/a&gt; to get these keys.'; } return null; } function allow_captcha() { return function_exists('fsockopen') &amp;&amp; strlen(trim(qa_opt('recaptcha_public_key'))) &amp;&amp; strlen(trim(qa_opt('recaptcha_private_key'))); } function form_html(&amp;$qa_content, $error) { require_once $this-&gt;directory.'recaptchalib.php'; $language=qa_opt('site_language'); if (strpos('|en|nl|fr|de|pt|ru|es|tr|', '|'.$language.'|')===false) // supported as of 3/2010 $language='en'; $qa_content['script_lines'][]=array( "var RecaptchaOptions={", "\ttheme:'white',", "\tlang:".qa_js($language), "};", ); return recaptcha_get_html(qa_opt('recaptcha_public_key'), $error, qa_is_https_probably()); } function validate_post(&amp;$error) { if ( (!empty($_POST['recaptcha_challenge_field'])) &amp;&amp; (!empty($_POST['recaptcha_response_field'])) ) { require_once $this-&gt;directory.'recaptchalib.php'; $answer=recaptcha_check_answer( qa_opt('recaptcha_private_key'), qa_remote_ip_address(), $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field'] ); if ($answer-&gt;is_valid) return true; $error=@$answer-&gt;error; } return false; } } </code></pre> <p>I am getting Internal Server Error because of that. What might be the issue? Please help me. Im sitting on this third day and I thought maybe I am missing something obvious.</p>
40,219,559
0
How to read latest email from Yahoo mail using pop3 c# <p>I want to read email from my yahoo mail account. I am using "OpenPop.Pop3" to read email from my yahoo mail account, I am using below code :-</p> <pre><code>using OpenPop.Pop3; public DataTable ReadEmailsFromId() { DataTable table = new DataTable(); try { using (Pop3Client client = new Pop3Client()) { client.Connect("pop.mail.yahoo.com", 995, true); //For SSL client.Authenticate("Username", "Password", AuthenticationMethod.UsernameAndPassword); int messageCount = client.GetMessageCount(); for (int i = messageCount; i &gt; 0; i--) { table.Rows.Add(client.GetMessage(i).Headers.Subject, client.GetMessage(i).Headers.DateSent); string msdId = client.GetMessage(i).Headers.MessageId; OpenPop.Mime.Message msg = client.GetMessage(i); OpenPop.Mime.MessagePart plainTextPart = msg.FindFirstPlainTextVersion(); string message = plainTextPart.GetBodyAsText(); } } } return table; } </code></pre> <p>Same code is able to access other mails emails like gmail,outlook but while working with yahoo mail emails i am able to get Subject, Date but when came to message part that is:</p> <pre><code>OpenPop.Mime.Message msg = client.GetMessage(i); OpenPop.Mime.MessagePart plainTextPart = msg.FindFirstPlainTextVersion(); </code></pre> <p>Its give error "The stream used to retrieve responses from was closed".</p> <p>Here is the "StackTrace":</p> <pre><code>at OpenPop.Pop3.Pop3Client.IsOkResponse(String response) at OpenPop.Pop3.Pop3Client.SendCommand(String command) at OpenPop.Pop3.Pop3Client.Disconnect() at OpenPop.Pop3.Pop3Client.Dispose(Boolean disposing) at OpenPop.Pop3.Disposable.Dispose() </code></pre> <p>Please let me know if i missing something or doing something wrong. Also I have make yahoo mail emails to be accessed anywhere using POP.</p>
6,528,617
0
<p>just extend <code>AndroidTestCase</code> instead of <code>ProviderTestCase2</code> AND use <code>getContext()</code></p>
1,279,464
0
<p>This is one of my favorite metaphors to describe software engineering:</p> <ul> <li><p>Imagine you're building a house. You'd have to have plans for the house, and decide what materials to build, and how to organize the building process. (Most people have had work done on their house so they have some rough concept of what's involved in this.)</p></li> <li><p>Now imagine that you're not building a house, you're building a skyscraper with 100 floors of offices. How would the plans be different than the plans for the house? How would the materials need to be different? What factors would need to be carefully considered?</p></li> <li><p>Now imagine that you're not building the skyscraper yourself, you're building a robot that will fly to the Moon and build the skyscraper there. Now how would the plans have to be different? How would the materials need to be different? Do you see why the ramifications of every decision would need to be carefully thought through?</p></li> </ul> <p>You could replace "skyscraper" with "freight management system" if you wanted, and I think the metaphor would still be useful.</p>
15,775,598
0
<pre><code>$array = array($one, $two, $three, $four, $five); foreach ($array as $value) { if ($example === $value) { something; } } </code></pre>
12,074,727
0
<p>This would be where you use Left Join and Group By. If all you need is the count of items from b, that is.</p> <pre><code>SELECT a.id id,a.price price,a.stock stock, a.max_per_user max_per_user,a.purchased purchased, COUNT(b.quantity owned) as quantity_owned FROM shop_items a LEFT JOIN shop_inventory b ON b.iid=a.id AND b.cid=a.cid WHERE a.cid=1 AND a.szbid=0 AND a.id IN(3,4) GROUP BY a.id </code></pre>
33,720,823
0
<p>you could have a list of letters and then filter on that - e.g:</p> <pre><code>var letters = new[] {"H","I", "J", "K", "L"}; var Artists = context.GetTable&lt;Artist&gt;().Where (a =&gt; letters.Any (l =&gt; a.Name.StartsWith(l))); </code></pre>
1,476,139
0
<p>I would second <a href="http://www.jqtouch.com/" rel="nofollow noreferrer">jQTouch</a>. It uses native CSS animations and behaves reasonably smoothly on my iPod Touch.</p>
20,134,891
0
SKPhysicsBody bodyWithPolygonFromPath memory leaks <p>I have a strange memory leaks when creating Sprite Kit physics bodies with custom shapes. This is how my implementation looks:</p> <pre><code>CGFloat offsetX = self.frame.size.width * self.anchorPoint.x; CGFloat offsetY = self.frame.size.height * self.anchorPoint.y; CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, 4 - offsetX, 3 - offsetY); CGPathAddLineToPoint(path, NULL, 66 - offsetX, 3 - offsetY); CGPathAddLineToPoint(path, NULL, 35 - offsetX, 57 - offsetY); CGPathCloseSubpath(path); self.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:path]; CGPathRelease(path); </code></pre> <p>Everything is going on inside <code>SKSpriteNode</code> method. Instruments tells me about several memory leaks after creating such bodies:</p> <pre><code>Leaked object: Malloc 32 Bytes Size: 32 Bytes Responsible Library: PhysicsKit Responsible Frame: std::__1::__split_buffer&lt;PKPoint, std::__1::allocator&lt;PKPoint&gt;&amp;&gt;::__split_buffer(unsigned long, unsigned long, std::__1::allocator&lt;PKPoint&gt;&amp;) </code></pre> <p>The <code>CGPathRelease(path);</code> line is necessary - without it I'm getting more memory leaks about <code>CGPath</code> which is understandable. When I'm using this implementation instead (for testing purposes):</p> <pre><code>CGFloat radius = MAX(self.frame.size.width, self.frame.size.height) * 0.5f; self.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:radius]; </code></pre> <p>...everything is working well, without memory leaks. I wonder if this is Sprite Kit bug or I'm doing something wrong.</p>
12,042,217
0
can you append(add) space and/or hyphen characters to the end of match in regex? <p>exactly as the question sounds, I want to know if you can append or add a space character at the end of all matches or just certain matches</p> <p>regex code I have</p> <pre><code>${Brand Name}${Colour}${Product Description}${ID} </code></pre> <p>what it spits out</p> <pre><code>Facille SnapBlackTablestop Snapkin Dispenser and Pack of Snapkins4696400 Brand Name: Facille Snap Colour: Black Product Description: Tablestop Snapkin Dispenser and Pack of Snapkins ID: 4696400 </code></pre> <p>I want regex to return a usable line of text like this</p> <pre><code>Facille Snap - Black Tablestop Snapkin Dispenser and Pack of Snapkins - 4696400 </code></pre>
23,066,290
0
MySQL - Query performance issues - taking 25+ seconds <p>I've been trying to figure out why this query is taking so long. Before, it was executing in approx 150ms to 200ms but now it's taking 25 seconds or longer. And this was between last night and this mroning. The only thing that's changed is add data to tables.</p> <p>Based on the explain output below and also the sql I've provided, is there anything that stands out that would explain why the query takes so long now?</p> <p>update: Per the comment from halfer, I changed the order by to <code>ORDER BY pins.pin_id</code> and it brought the execution time to 172ms.</p> <p>Also, I wanted to mention that the table pins has 20 million records, boards as 339,000 records, users has 352738 records.</p> <pre><code>+----+--------------------+---------------+-----------------+----------------------------------------------+---------+---------+--------------------------------+------+--------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+--------------------+---------------+-----------------+----------------------------------------------+---------+---------+--------------------------------+------+--------------------------+ | 1 | PRIMARY | &lt;derived11&gt; | system | NULL | NULL | NULL | NULL | 1 | | | 1 | PRIMARY | pins | index | user_id,user_id_2,latitude,longitude,lat_lon | vip | 1 | NULL | 646 | Using where | | 1 | PRIMARY | users | eq_ref | PRIMARY | PRIMARY | 8 | skoovy_prd.pins.user_id | 1 | | | 1 | PRIMARY | boards | eq_ref | PRIMARY | PRIMARY | 8 | skoovy_prd.pins.board_id | 1 | | | 1 | PRIMARY | via | eq_ref | PRIMARY | PRIMARY | 8 | skoovy_prd.pins.via | 1 | | | 12 | DEPENDENT SUBQUERY | users | unique_subquery | PRIMARY | PRIMARY | 8 | func | 1 | Using where | | 11 | DERIVED | NULL | NULL | NULL | NULL | NULL | NULL | NULL | No tables used | | 10 | DEPENDENT SUBQUERY | users_avatars | ref | pin_id | pin_id | 14 | skoovy_prd.users.user_id,const | 1 | Using where | | 9 | DEPENDENT SUBQUERY | users_avatars | ref | pin_id | pin_id | 14 | skoovy_prd.users.user_id,const | 1 | Using where | | 8 | DEPENDENT SUBQUERY | users_avatars | ref | pin_id | pin_id | 14 | skoovy_prd.users.user_id,const | 1 | Using where | | 7 | DEPENDENT SUBQUERY | pins_images | ref | pin_id | pin_id | 14 | skoovy_prd.pins.pin_id,const | 1 | Using where | | 6 | DEPENDENT SUBQUERY | pins_images | ref | pin_id | pin_id | 14 | skoovy_prd.pins.pin_id,const | 1 | Using where | | 5 | DEPENDENT SUBQUERY | pins_images | ref | pin_id | pin_id | 14 | skoovy_prd.pins.pin_id,const | 1 | Using where | | 4 | DEPENDENT SUBQUERY | pins_images | ref | pin_id | pin_id | 14 | skoovy_prd.pins.pin_id,const | 1 | Using where | | 3 | DEPENDENT SUBQUERY | pins_reports | index | user_id | user_id | 115 | NULL | 1 | Using where; Using index | | 2 | DEPENDENT SUBQUERY | pins_likes | ref | pin_id,pin_id_2,user_id | pin_id | 16 | skoovy_prd.pins.pin_id,const | 1 | Using index | +----+--------------------+---------------+-----------------+----------------------------------------------+---------+---------+--------------------------------+------+--------------------------+ </code></pre> <p>The SQL:</p> <pre><code>SELECT `pins`.`pin_id` AS `pin_pin_id`, `pins`.`check_unique_id` AS `pin_check_unique_id`, `pins`.`category_id` AS `pin_category_id`, `pins`.`board_id` AS `pin_board_id`, `pins`.`user_id` AS `pin_user_id`, `pins`.`date_added` AS `pin_date_added`, `pins`.`date_modified` AS `pin_date_modified`, `pins`.`likes` AS `pin_likes`, `pins`.`comments` AS `pin_comments`, `pins`.`repins` AS `pin_repins`, `pins`.`description` AS `pin_description`, `pins`.`title` AS `pin_title`, `pins`.`image` AS `pin_image`, `pins`.`price` AS `pin_price`, `pins`.`price_currency_code` AS `pin_price_currency_code`, `pins`.`price_type` AS `pin_price_type`, `pins`.`price_from` AS `pin_price_from`, `pins`.`price_to` AS `pin_price_to`, `pins`.`event_type` AS `pin_event_type`, `pins`.`event_start` AS `pin_event_start`, `pins`.`event_end` AS `pin_event_end`, `pins`.`from` AS `pin_from`, `pins`.`from_md5` AS `pin_from_md5`, `pins`.`from_repin` AS `pin_from_repin`, `pins`.`is_video` AS `pin_is_video`, `pins`.`views` AS `pin_views`, `pins`.`latest_comments` AS `pin_latest_comments`, `pins`.`source_id` AS `pin_source_id`, `pins`.`via` AS `pin_via`, `pins`.`repin_from` AS `pin_repin_from`, `pins`.`public` AS `pin_public`, `pins`.`ub_id` AS `pin_ub_id`, `pins`.`total_views` AS `pin_total_views`, `pins`.`delete_request` AS `pin_delete_request`, `pins`.`pinmarklet` AS `pin_pinmarklet`, `pins`.`vip` AS `pin_vip`, `pins`.`store` AS `pin_store`, `pins`.`width` AS `pin_width`, `pins`.`height` AS `pin_height`, `pins`.`ext` AS `pin_ext`, `pins`.`location` AS `pin_location`, `pins`.`latitude` AS `pin_latitude`, `pins`.`longitude` AS `pin_longitude`, IF(pins.price_type != '' AND (pins.price_type = 'CUSTOM_RANGE' AND pins.price_from &lt;&gt; 0.00 AND pins.price_to &lt;&gt; 0.00 AND pins.price_from &lt; pins.price_to) OR (pins.price_from &lt;&gt; 0.00), 1, 0) AS `pin_show_pricing`, IF(pins.price_type = 'CUSTOM_RANGE', CONCAT('$', pins.price_from, '-', '$', pins.price_to), CONCAT('$', pins.price_from)) AS `pin_price_text`, IF((pins.event_start IS NOT NULL || pins.event_end IS NOT NULL) &amp;&amp; (pins.event_start != '0000-00-00 00:00:00' || pins.event_end != '0000-00-00 00:00:00') &amp;&amp; (event_type = 'multiple' || event_type = 'single'), 1, 0) AS `pin_show_event`, IF(pins.event_type = 'multiple', CONCAT(DATE_FORMAT(pins.event_start, '%Y-%m-%d'), ' - ', DATE_FORMAT(pins.event_end, '%Y-%m-%d')), DATE_FORMAT(pins.event_start, '%Y-%m-%d')) AS `pin_event_text`, (SELECT COUNT(like_id) FROM `pins_likes` WHERE (pin_id = pins.pin_id) AND (user_id = 57610) LIMIT 1) AS `pin_is_liked`, (SELECT COUNT(pr_id) FROM `pins_reports` WHERE (pin_id = pins.pin_id) AND (checked = 0) AND (user_id = '57610' OR user_ip = '44021cb8') LIMIT 1) AS `pin_is_reported`, (SELECT CONCAT_WS('|||', image, width, height, original, mime) FROM `pins_images` WHERE (pin_id = pins.pin_id) AND (size = '_A') LIMIT 1) AS `pin_thumb_a`, (SELECT CONCAT_WS('|||', image, width, height, original, mime) FROM `pins_images` WHERE (pin_id = pins.pin_id) AND (size = '_B') LIMIT 1) AS `pin_thumb_b`, (SELECT CONCAT_WS('|||', image, width, height, original, mime) FROM `pins_images` WHERE (pin_id = pins.pin_id) AND (size = '_C') LIMIT 1) AS `pin_thumb_c`, (SELECT CONCAT_WS('|||', image, width, height, original, mime) FROM `pins_images` WHERE (pin_id = pins.pin_id) AND (size = '_D') LIMIT 1) AS `pin_thumb_d`, `users`.`user_id` AS `user_user_id`, `users`.`source` AS `user_source`, `users`.`source_uuid` AS `user_source_uuid`, `users`.`is_business` AS `user_is_business`, `users`.`username` AS `user_username`, `users`.`password` AS `user_password`, `users`.`email` AS `user_email`, `users`.`new_email` AS `user_new_email`, `users`.`new_email_key` AS `user_new_email_key`, `users`.`business_name` AS `user_business_name`, `users`.`business_phone` AS `user_business_phone`, `users`.`firstname` AS `user_firstname`, `users`.`lastname` AS `user_lastname`, `users`.`groups` AS `user_groups`, `users`.`status` AS `user_status`, `users`.`last_action_datetime` AS `user_last_action_datetime`, `users`.`last_login` AS `user_last_login`, `users`.`ip_address` AS `user_ip_address`, `users`.`following` AS `user_following`, `users`.`followers` AS `user_followers`, `users`.`avatar` AS `user_avatar`, `users`.`facebook_id` AS `user_facebook_id`, `users`.`twitter_id` AS `user_twitter_id`, `users`.`twitter_username` AS `user_twitter_username`, `users`.`is_admin` AS `user_is_admin`, `users`.`is_developer` AS `user_is_developer`, `users`.`gender` AS `user_gender`, `users`.`location` AS `user_location`, `users`.`latitude` AS `user_latitude`, `users`.`longitude` AS `user_longitude`, `users`.`website` AS `user_website`, `users`.`date_added` AS `user_date_added`, `users`.`new_password` AS `user_new_password`, `users`.`new_password_key` AS `user_new_password_key`, `users`.`facebook_session` AS `user_facebook_session`, `users`.`boards` AS `user_boards`, `users`.`pins` AS `user_pins`, `users`.`likes` AS `user_likes`, `users`.`latest_pins` AS `user_latest_pins`, `users`.`description` AS `user_description`, `users`.`facebook_connect` AS `user_facebook_connect`, `users`.`facebook_timeline` AS `user_facebook_timeline`, `users`.`twitter_connect` AS `user_twitter_connect`, `users`.`dont_search_index` AS `user_dont_search_index`, `users`.`delete_account` AS `user_delete_account`, `users`.`delete_account_date` AS `user_delete_account_date`, `users`.`groups_pin_email` AS `user_groups_pin_email`, `users`.`comments_email` AS `user_comments_email`, `users`.`likes_email` AS `user_likes_email`, `users`.`repins_email` AS `user_repins_email`, `users`.`follows_email` AS `user_follows_email`, `users`.`email_interval` AS `user_email_interval`, `users`.`digest_email` AS `user_digest_email`, `users`.`news_email` AS `user_news_email`, `users`.`first_login` AS `user_first_login`, `users`.`store` AS `user_store`, `users`.`width` AS `user_width`, `users`.`height` AS `user_height`, `users`.`instagram_connect` AS `user_instagram_connect`, `users`.`instagram_profile_id` AS `user_instagram_profile_id`, `users`.`instagram_token` AS `user_instagram_token`, `users`.`enable_follow` AS `user_enable_follow`, `users`.`public` AS `user_public`, users.username AS `user_fullname`, (SELECT CONCAT_WS('|||', image, width, height, original, mime) FROM `users_avatars` WHERE (user_id = users.user_id) AND (size = '_A') LIMIT 1) AS `user_avatar_a`, (SELECT CONCAT_WS('|||', image, width, height, original, mime) FROM `users_avatars` WHERE (user_id = users.user_id) AND (size = '_B') LIMIT 1) AS `user_avatar_b`, (SELECT CONCAT_WS('|||', image, width, height, original, mime) FROM `users_avatars` WHERE (user_id = users.user_id) AND (size = '_C') LIMIT 1) AS `user_avatar_c`, `boards`.`board_id` AS `board_board_id`, `boards`.`category_id` AS `board_category_id`, `boards`.`user_id` AS `board_user_id`, `boards`.`image` AS `board_image`, `boards`.`date_added` AS `board_date_added`, `boards`.`date_modified` AS `board_date_modified`, `boards`.`sort_order` AS `board_sort_order`, `boards`.`title` AS `board_title`, `boards`.`description` AS `board_description`, `boards`.`followers` AS `board_followers`, `boards`.`pins` AS `board_pins`, `boards`.`public` AS `board_public`, `boards`.`latest_pins` AS `board_latest_pins`, `boards`.`cover` AS `board_cover`, `boards`.`delete_request` AS `board_delete_request`, `boards`.`views` AS `board_views`, `boards`.`total_views` AS `board_total_views`, `via`.`user_id` AS `via_user_id`, `via`.`source` AS `via_source`, `via`.`source_uuid` AS `via_source_uuid`, `via`.`is_business` AS `via_is_business`, `via`.`username` AS `via_username`, `via`.`password` AS `via_password`, `via`.`email` AS `via_email`, `via`.`new_email` AS `via_new_email`, `via`.`new_email_key` AS `via_new_email_key`, `via`.`business_name` AS `via_business_name`, `via`.`business_phone` AS `via_business_phone`, `via`.`firstname` AS `via_firstname`, `via`.`lastname` AS `via_lastname`, `via`.`groups` AS `via_groups`, `via`.`status` AS `via_status`, `via`.`last_action_datetime` AS `via_last_action_datetime`, `via`.`last_login` AS `via_last_login`, `via`.`ip_address` AS `via_ip_address`, `via`.`following` AS `via_following`, `via`.`followers` AS `via_followers`, `via`.`avatar` AS `via_avatar`, `via`.`facebook_id` AS `via_facebook_id`, `via`.`twitter_id` AS `via_twitter_id`, `via`.`twitter_username` AS `via_twitter_username`, `via`.`is_admin` AS `via_is_admin`, `via`.`is_developer` AS `via_is_developer`, `via`.`gender` AS `via_gender`, `via`.`location` AS `via_location`, `via`.`latitude` AS `via_latitude`, `via`.`longitude` AS `via_longitude`, `via`.`website` AS `via_website`, `via`.`date_added` AS `via_date_added`, `via`.`new_password` AS `via_new_password`, `via`.`new_password_key` AS `via_new_password_key`, `via`.`facebook_session` AS `via_facebook_session`, `via`.`boards` AS `via_boards`, `via`.`pins` AS `via_pins`, `via`.`likes` AS `via_likes`, `via`.`latest_pins` AS `via_latest_pins`, `via`.`description` AS `via_description`, `via`.`facebook_connect` AS `via_facebook_connect`, `via`.`facebook_timeline` AS `via_facebook_timeline`, `via`.`twitter_connect` AS `via_twitter_connect`, `via`.`dont_search_index` AS `via_dont_search_index`, `via`.`delete_account` AS `via_delete_account`, `via`.`delete_account_date` AS `via_delete_account_date`, `via`.`groups_pin_email` AS `via_groups_pin_email`, `via`.`comments_email` AS `via_comments_email`, `via`.`likes_email` AS `via_likes_email`, `via`.`repins_email` AS `via_repins_email`, `via`.`follows_email` AS `via_follows_email`, `via`.`email_interval` AS `via_email_interval`, `via`.`digest_email` AS `via_digest_email`, `via`.`news_email` AS `via_news_email`, `via`.`first_login` AS `via_first_login`, `via`.`store` AS `via_store`, `via`.`width` AS `via_width`, `via`.`height` AS `via_height`, `via`.`instagram_connect` AS `via_instagram_connect`, `via`.`instagram_profile_id` AS `via_instagram_profile_id`, `via`.`instagram_token` AS `via_instagram_token`, `via`.`enable_follow` AS `via_enable_follow`, `via`.`public` AS `via_public`, via.username AS `via_fullname`, `row` . *, @curRow:=@curRow + 1 AS `pin_pin_row` FROM `pins` LEFT JOIN `users` ON pins.user_id = users.user_id LEFT JOIN `boards` ON pins.board_id = boards.board_id LEFT JOIN `users` AS `via` ON pins.via = via.user_id INNER JOIN (SELECT @curRow:=- 1) AS `row` WHERE (pins.user_id = 57610 OR IF(pins.user_id = 57610, 1, pins.public) = 1) AND (pins.latitude &lt;= 40.78666477795 AND pins.latitude &gt;= 40.64193322205 AND pins.longitude &lt;= - 73.910342436525 AND pins.longitude &gt;= - 74.101288363475) AND (pins.user_id = 57610 OR pins.user_id IN (SELECT user_id FROM users WHERE public = 1)) ORDER BY pins.vip DESC , pins.pin_id DESC LIMIT 30 </code></pre>
6,272,043
0
How to get custom attributes on .to_json method? <p>For example, i've this model:</p> <pre><code>class User &lt; ActiveRecord::Base def foo bar end end </code></pre> <p>When i do this: &lt;%= User.all.to_json %></p> <p>I get this:</p> <p>[{"user":{"created_at":"2011-06-07T17:40:21-03:00","login":"abcd", "password":"1234","updated_at":"2011-06-07T18:10:04-03:00"}}]</p> <p>How can i get foo on this json too? Also, foo is an activerecord too..</p> <p>Thanks</p>
29,792,746
0
<p>This maybe a difficult one for someone with limited Alfresco knowledge, so hopefully you'll understand it.</p> <ol> <li>You'll need to create a repository webscript which takes as input a site and uses siteService methods to get the members and groups. You can peak at the siteMembers Share page which probably uses something similar to show the members and groups. And you'll probably will need to make it searchable :).</li> <li>Change the current custom control which uses the default picker to select users/groups. Probably you'll only need to change the repository webscript url so it goes to the right new webscript. If you don't want to make any more changes, be sure to present the output in the exact same way.</li> <li>You can start a workflow from you personal dashboard of from the my-workflow pages, so there is not always a site. And even if you're starting from a site big changes the site doesn't get passed to the start-workflow page. So you'll need to get the destination nodeRef (the node you're starting the workflow on) send it as param to your repository webscript and let it determine which site it is in.</li> </ol> <p>First change the custom control which selects the assignee. This control goes to a repository webscript which shows/searches all the users/groups.</p>
961,085
0
<p>There are exactly two relations with no attributes, one with an empty tuple, and one without. In <a href="http://en.wikipedia.org/wiki/The_Third_Manifesto" rel="nofollow noreferrer">The Third Manifesto</a>, Date and Darwen (somewhat) humorously name them <code>TABLE_DEE</code> and <code>TABLE_DUM</code> (respectively).</p> <p>They are useful to the extent that they are the identity of a variety of relational operators, playing roles equivalent to 1 and 0 in ordinary algebra.</p>
17,089,584
0
Why can't I emplace ifstreams in a vector? <p>The following example program doesn't compile for me on either clang 3.1 or gcc 4.8:</p> <pre><code>#include &lt;fstream&gt; #include &lt;vector&gt; using namespace std; int main() { vector&lt;ifstream&gt; bla; bla.emplace_back("filename"); return 0; } </code></pre> <p>However, I thought emplace_back should </p> <blockquote> <p>"Insert a new element at the end of the vector, right after its current last element. This new element is constructed in place using args as the arguments for its construction."</p> </blockquote> <p>Does anyone know why this doesn't compile then? did I misunderstand or are the library implementations not yet complete?</p>
23,913,212
0
<p>Please change your </p> <pre><code>default_validation_class = UTF8Type to default_validation_class = LongType </code></pre> <p>It should work.</p>
5,907,853
0
<p>@jason;</p> <p>i saw it in IE may you have to define <code>width</code> <code>like width:200px;</code> to your #footerdetails div because in IE7 it's take <code>width 100%</code> of the screen.</p> <p>css</p> <pre><code>#footerdetails { color: #FFFFFF; display: block; height: 100px; left: 0; position:fixed; text-align: right; top: 0; width: 200px; z-index: 100; } </code></pre>
17,796,347
0
<p>Unfortunately, no, this isn't currently possible in an official or supported way. These shared links don't offer any metadata or API for access like this.</p>
1,797,502
0
Is there a scala identity function? <p>If I have something like a <code>List[Option[A]]</code> and I want to convert this into a <code>List[A]</code>, the standard way is to use <code>flatMap</code>:</p> <pre><code>scala&gt; val l = List(Some("Hello"), None, Some("World")) l: List[Option[java.lang.String]] = List(Some(Hello), None, Some(World)) scala&gt; l.flatMap( o =&gt; o) res0: List[java.lang.String] = List(Hello, World) </code></pre> <p>Now <code>o =&gt; o</code> is just an identity function. I would have thought there'd be some way to do:</p> <pre><code>l.flatMap(Identity) //return a List[String] </code></pre> <p>However, I can't get this to work as you can't generify an <code>object</code>. I tried a few things to no avail; has anyone got something like this to work?</p>
7,171,015
0
<p>Well you could use python itself to reverse the line through the filter command. Say the text you had written was: </p> <pre><code>Python </code></pre> <p>You could reverse it by issuing.</p> <pre><code>:1 ! python -c "print raw_input()[::-1]" </code></pre> <p>And your text will be replaced to become:</p> <pre><code>nohtyP </code></pre> <p>The "1" in the command tells vi to send line 1 to the python statement which we are executing: "print raw_input()[::-1]". So if you wanted some other line reversed, you would send that line number as argument. The python statement then reverses the line of input. </p>
19,262,644
0
How to pass a NSMutableArray including NSManagedObjects to another view controller? <p>I embedded 'Core Data' into my app. I use a predicate and fetch the result. I use a mutableArray called "fetchedObjects" to get the (predicated and then fetched) result. Now I need to pass this result to another view controller. How can I do that?</p> <p>1.First thing I tried is using 'NSCoding' but it didn't work out. I think Core Data doesn't comply with NSCoding, am I right? </p> <p>If I can use 'NSCoding', how do I do it? I tried to save and then load the fetchedObjects but it didn't work out.</p> <p>2.Off course I can define a pointer using </p> <pre><code>"product = [[Product alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];" </code></pre> <p>but how can I get just the "fetchedObjects" mutableArray but not all the objects?</p> <p>3.Do you know a better way to pass a NSMutableArray having NSManagedObjects in it? and how can we pass the NSManagedObjects to the other view controllers, only in the context?</p> <p>Thanks!</p>
12,114,308
0
Table view button shows up after I scroll down page one time <p>I am trying to add a custom radio button to each cell in a table view. When I first view the table view, I can't see any radio button. But when I scroll down I can see radio buttons on each cell underneath the initial cells that are seen when the view is first loaded. And once a cell that didn't have a radio button on it goes out of view, and I go back to view that cell, the radio button appears.</p> <p>Here is my code for this one method:</p> <pre><code> - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *ImageCellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ImageCellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ImageCellIdentifier]; cell.accessoryType = UITableViewCellAccessoryNone; } _radioBtn.frame = CGRectMake(275, 3,36,36); _radioBtn = [UIButton buttonWithType:UIButtonTypeCustom]; [_radioBtn setImage:[UIImage imageNamed:@"Radio-Btn.png"] forState:UIControlStateNormal]; [cell.contentView addSubview:_radioBtn]; NSString *cellValue = [_arrayRelat objectAtIndex:indexPath.row]; cell.textLabel.text = cellValue; cell.textLabel.textColor = [UIColor colorWithRed:(88.0/255.0) green:(88.0/255.0) blue:(89.0/255.0) alpha:1]; return cell; } </code></pre> <p>Let me know if you don't understand the question.</p>
38,828,203
0
<p>I solved it by going with gulp-tap.</p> <pre><code>conf.plugScss.files.forEach(function (file, index, files) { gulp.src(file) .pipe(rename({ prefix: "_", extname: ".scss" })) .pipe(tap(function (file, t) { file.contents = Buffer.concat([ new Buffer('HEADER'), file.contents ]); var fileCheck = function(err, stat) { if (err !== null &amp;&amp; err.code == 'ENOENT') { fs.writeFile('dist/' + file.path.split('/').reverse()[0], file.contents) } return null; } fs.stat('dist/' + file.path.split('/').reverse()[0], fileCheck.bind(this)); })); // for when gulp 4.0 releases // .pipe(gulp.dest(conf.plugScss.dist, {overwrite: false})) }); </code></pre>
16,823,573
0
netbeans c++ with mysql windows <p>I am using netbeans 7 (c++) to connect to mySQL using Boost libraries (boost_1_53_0) and the required mySql C++ libraries (include and Lib) I added the path of the libraries in the project properties->C++ Compiler->include directories.</p> <p>I also added the path of the libraries in project properties->linker->include directories. Finally I added the mysqlcppconn.dll to project properties->linker->libraries</p> <p>this is the program: I'm just testing </p> <pre><code>#include &lt;cstdlib&gt; using namespace std; #include "cppconn/driver.h" #include "cppconn/connection.h" /* */ int main(int argc, char** argv) { sql::Driver *driver ; sql ::Connection *conn; driver = get_driver_instance(); conn = driver-&gt;connect("localhost","root","1qaz"); return 0; } </code></pre> <p>I've got this error at the output: /cygdrive/c/Users/NetBeansProjects/CppApplication_3/dist/Debug/Cy gwin-Windows/cppapplication_3.exe: error while loading shared libraries: mysqlcp pconn.dll: cannot open shared object file: No such file or directory</p> <p>I tried some of the suggested solutions about icluding the libraries but it still nothing any suggestions</p>
39,631,439
0
Receiving Domain Emails using Amazon AWS SES <p>I am using AWS SES for sending emails using my domain name. The sending works fine. But now I want to receive all the emails sent using my domain like [email protected] in SES.</p> <p>I am trying to receive emails using rule set defined to execute Lambda function or to store emails in S3 bucket.</p> <p>When I try to send email using gmail to my domain email, it is not received in S3 bucket and Lambda function is also not executed.</p> <p>I have done following things so far:</p> <ol> <li><p>Verified my domain with SES, (CNAME, TXT entries on my DNS provider i.e. GoDaddy)</p> <p>Added MX record for my domain in DNS settings</p> <p>Defined rule set for receiving emails for [email protected] &amp; store emails in S3 bucket.</p></li> </ol> <p>Right now when I send email to this address I don't get anything in S3 bucket. I don't even receive delivery failure notification (This means MX record is working fine with my domain provider)</p> <p>Please help.</p>
19,320,063
0
Installing ElasticSearch on Nitrous.io? <p>I'm trying to use Elasticsearch on Nitrous.io.</p> <p>I'm following <a href="https://shellycloud.com/blog/2013/10/adding-search-and-autocomplete-to-a-rails-app-with-elasticsearch" rel="nofollow">this tutorial</a> but when trying to reindex the model I get this error</p> <pre><code>action@learning-rails-1868:~/fayl$ rake searchkick:reindex CLASS=Fail rake aborted! Connection refused - connect(2) /home/action/.rvm/gems/ruby-1.9.3-p374/gems/rest-client-1.6.7/lib/restclient/request.rb:172:in `transmit' /home/action/.rvm/gems/ruby-1.9.3-p374/gems/rest-client- 1.6.7/lib/restclient/request.rb:64:in `execute' /home/action/.rvm/gems/ruby-1.9.3-p374/gems/tire-0.6.0/lib/tire/http/client.rb:11:in `get' /home/action/.rvm/gems/ruby-1.9.3-p374/gems/searchkick-0.2.8/lib/searchkick/reindex.rb:43:in `clean_indices' /home/action/.rvm/gems/ruby-1.9.3-p374/gems/searchkick-0.2.8/lib/searchkick/reindex.rb:10:in `reindex' /home/action/.rvm/gems/ruby-1.9.3-p374/gems/searchkick-0.2.8/lib/searchkick/tasks.rb:10:in `block (2 levels) in &lt;top (required)&gt;' /home/action/.rvm/gems/ruby-1.9.3-p374/bin/ruby_noexec_wrapper:14:in `eval' /home/action/.rvm/gems/ruby-1.9.3-p374/bin/ruby_noexec_wrapper:14:in `&lt;main&gt;' Tasks: TOP =&gt; searchkick:reindex </code></pre> <p>I'm not sure I've installed Elasticsearch on Nitrous.io properly. Has anyone managed to do this successfully? Or can you point to a guide for how to implement this?</p>
23,318,854
1
Python program using lists <p>I am trying to write a program that displays an employee's id, their hours, payrate, and wages. </p> <p>The second part of the program requires that the user enter an employee's Id so that their wage will be displayed. </p> <p>The first part of my program works fine up until <code>pay=input()</code>. When I try to run it with the second part, it says that there is a syntax error. </p> <p>Here is my program:</p> <pre><code>employeeId=[56588,45201,78951,87775,84512,13028,75804] hours=[40,41,42,43,44,45,46] payrate=[13.60,13.50,13.40,13.30,13.20,13.10,13.00] wages=[544.00,553.50,562.80,571.90,580.80,589.50,598.00] print('employeeId\thours\t\tpayRate\t\twages') print(employeeId[0],'\t\t',hours[0],'\t\t',payrate[0],'\t\t',wages[0]) print(employeeId[1],'\t\t', hours[1],'\t\t',payrate[1],'\t\t',wages[1]) print(employeeId[2],'\t\t',hours[2],'\t\t',payrate[2],'\t\t',wages[2]) print(employeeId[3],'\t\t',hours[3],'\t\t',payrate[3],'\t\t',wages[3]) print(employeeId[4],'\t\t',hours[4],'\t\t',payrate[4],'\t\t',wages[4]) print(employeeId[5],'\t\t',hours[5],'\t\t',payrate[5],'\t\t',wages[5]) print(employeeId[6],'\t\t',hours[6],'\t\t',payrate[6],'\t\t',wages[6]) pay=input("Would you like to a see a specific employee's gross pay? Y/N:") if pay=='Y'or pay=='y': ID=input('enter employee Id:') if ID=='56588': print(ID': $',wages[0]) elif ID=='45201': print(ID': $',wages[1]) elif ID=='78951': print(ID': $',wages[2]) elif ID=='87775': print(ID': $',wages[3]) elif ID=='84512': print(ID': $',wages[4]) elif ID=='13028': print(ID': $',wages[5]) elif ID=='75804': print(ID': $',wages[6]) else: print(' ') </code></pre> <p>I'm seeing the following syntax error:</p> <pre><code> File "code.py", line 19 print(ID': $',wages[0]) ^ SyntaxError: invalid syntax </code></pre>
7,667,601
0
<p>Why not store the passwords in the database with SHA1, then use HMAC with a client specified key for the communication?</p> <p>Have the server generate a random key and send it with the login request. The client computes the SHA1 hash of the password, then computes the HMAC SHA1 hash of that using the server-specified key. The server then verifies that the result is correct.</p> <p>On the client end:</p> <pre><code>// password is the plaintext password // keyb64 is a random key specified by the server, encoded in base64. string ComputeSecureHash(string password, string keyb64) { byte[] data = Encoding.UTF8.GetBytes(password); byte[] key = Convert.FromBase64String(keyb64); byte[] hash; byte[] machash; // compute a plain SHA1 hash of the specified data using (SHA1Managed sha1 = new SHA1Managed()) { hash = sha1.ComputeHash(data); } // now compute a HMAC hash of that hash, using the random key. using (HMACSHA1 sha1mac = new HMACSHA1(key)) { machash = sha1mac.ComputeHash(hash); } return Convert.ToBase64String(machash); } </code></pre> <p>On the server end:</p> <pre><code>// hash is the string produced by the function above // realHash is the SHA1 hash of the real password, which you've fetched from the db // key is the key you generated for this login session bool VerifyHash(string hash, byte[] realHash, byte[] key) { byte[] machash; using (HMACSHA1 sha1mac = new HMACSHA1(key)) { machash = sha1mac.ComputeHash(realHash); } return (Convert.ToBase64String(machash) == hash); } </code></pre> <p>This allows you to authenticate over a plaintext medium without having the password cracked. </p>
25,063,655
0
<p>I've had this had this problem too. I save most of my SVG files from Adobe Illustrator. For whatever reason it tacked in <code>overflow="scroll"</code> in the SVG tag on a few of my files. Removing this fixed the problem for me.</p>
24,859,051
0
<p>It is a shorthand way to reference to the route, by using</p> <pre><code>@Html.RouteLink("Privacy"); </code></pre> <p>Here an article on ASP.NET about routing, which helped me a lot...</p> <p><a href="http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs">ASP.NET MVC Routing Overview (C#)</a></p>
33,462,384
0
<p>The <code>tsplot</code> of seaborn is not meant to plot a simple timeseries line plot, but to plot uncertainties, see:<a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.tsplot.html">https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.tsplot.html</a>. </p> <p>For a line plot, you can simply do</p> <pre><code>df.set_index('Date').plot() </code></pre>
27,330,514
0
Continuing sessions using JSESSIONID <p>I have a web application which requires <code>username and password authentication</code> to enter.</p> <p>What I am doing is, authenticate a user from a stand alone <code>Java app</code>, which would do so by making <code>Http</code> request to the server using <code>username</code> and <code>password</code>. Then I would retrieve <code>JSESSIONID</code> cookie from response of server.</p> <p>Now what I want is to use this <code>JSESSIONID</code> to continue session on browser i.e. to let <code>user</code> navigate pages of my web app which would be opened by my stand alone java app which I use for authentication.</p> <p><strong>Is this possible?</strong> Or is there any other way to do so.</p>
21,812,622
0
<p>Try with something like this</p> <pre><code>db.collectionName.find({:barsIds =&gt; {"$in" =&gt; BSON::ObjectId("5300c6ba4a5ce5614bcd5d9a")}}) </code></pre>
17,836,637
0
<p>If you're happy to just update the database at the end, you can get the job name and run time from the <code>IJobExecutionContext</code>:</p> <pre><code>public void JobWasExecuted(JobExecutionContext context, JobExecutionException jobException) { var sql = @"INSERT INTO MyJobAuditHistory (JobKey, RunTime, Status, Exception) VALUES (?, ?, ?, ?)"; // create command etc. command.Parameters.Add(context.JobDetail.Key.ToString()); command.Parameters.Add(context.JobRunTime); command.Parameters.Add(jobException == null ? "Success" : "Fail"); command.Parameters.Add(jobException == null ? null : jobException.Message); } </code></pre>
39,790,991
0
<p>The best way to do this (in my opinion) is to actually combine @serge1peshcoff's two options. Write the call as a function that calls itself when the response fails, <em>and</em> set a timeout when doing so. For most purposes, you don't want to send another request immediately after the previous one, you want to wait at least a second or five to prevent spamming the server (you've also given no indication of how many clients you expect. What's bad for your browser is potentially horrible for the server, which may be handling requests even before your web app is fully up and returning 200). </p> <p>Also, setTimeout is a better approach than setInterval, as you explicitly reset it on each round trip. </p> <p>Borrowing from @serge:</p> <pre><code>function tryRequest(numTries) { var responseStatus = 404; var request = new XMLHttpRequest(); numTries = numTries || 0; console.log("Checking if restart has completed. Attempt number: " + numAttempts); request.open('GET', 'applicationurl', true); request.onreadystatechange = function(){ numTries++ if (request.readyState === 4){ console.log("Request Status: " + request.status); responseStatus = request.status; console.log("Response Status: " + request.status); if (request.status != 200) { console.log("Restart has not yet completed! NumberOfTries: " + this.attempts); setTimeout(tryRequest.bind(null, numTries), 5000); // five seconds } } }; request.send(); console.log("Server has successfully restarted"); } tryRequest(); </code></pre>
37,114,120
0
<p>Use this <a href="http://stackoverflow.com/questions/35050746/web-scraping-how-to-access-content-rendered-in-javascript-via-angular-js">link</a> to get a better overview. <br/> To answer your question more precisely, <strong>Paytm</strong> gets data in js files about the product. Following link gives data about any product listed at <strong>Paytm</strong>: <br/> <a href="https://catalog.paytm.com/v1/p/" rel="nofollow">https://catalog.paytm.com/v1/p/</a><strong>product-url</strong>&amp;callback=angular.callbacks._0&amp;channel=web&amp;version=2 <br/> The link given by you: <br/> <a href="https://paytm.com/shop/p/masha-mauve-satin-nighty-WNIGHW000NT14_45BBPPFR?src=search-grid&amp;tracker=autosuggest%7Cundefined%7Cmasha%20nighty%7Cgrid%7CSearch%7C1" rel="nofollow">https://paytm.com/shop/p/masha-mauve-satin-nighty-WNIGHW000NT14_45BBPPFR?src=search-grid&amp;tracker=autosuggest%7Cundefined%7Cmasha%20nighty%7Cgrid%7CSearch%7C1</a>. <br/> <strong>product-url</strong> : <br/> masha-mauve-satin-nighty-WNIGHW000NT14_45BBPPFR?src=search-grid&amp;tracker=autosuggest%7Cundefined%7Cmasha%20nighty%7Cgrid%7CSearch%7C1 <br/> Hope it helps you.</p>
16,272,185
0
<p>I ran into this over the weekend at a hackathon on Mac OSX - took me a solid 4 hours to piece everything together despite having a few reference materials (mentioned at the end). I didn't find an easy walk-through, so I decided to post one while it is fresh in my mind.</p> <p>I'm not sure of the compatibility with Windows, but hopefully these instructions will make it easier for you too.</p> <p>I was trying to get R and MySQL to communicate in a local environment (there may need to be changes for a server environment). I use XAMPP (though I didn't use RMySQL for the connection), but in the end I was able to use a PHP page to write an R file, execute that file, and have R write to a MySQL table. To the best of my knowledge this only works for MacOSX...</p> <p>All software used was in dmg form so no binary installs necessary.</p> <ol> <li><p><a href="https://cran.r-project.org/bin/macosx/" rel="nofollow noreferrer">Download R</a> and run some basic commands to make sure that you have it working.</p></li> <li><p>In R, you need to install RODBC (if you don't have it already). Type this into the R console.</p></li> </ol> <pre><code>install.packages("RODBC") </code></pre> <p>This installs RODBC, but since OS Mavericks, certain files are no longer included, so you get an error message </p> <blockquote> <p>ODBC headers sql.h and sqlext.h not found</p> </blockquote> <p>and you need to get the sql.h and sqlext.h files in the right place.</p> <p>To do this the easiest way, make sure that you have <a href="http://brew.sh/" rel="nofollow noreferrer">homebrew</a> installed (easy instructions). Then use this <a href="http://stackoverflow.com/a/29214529/2330917">code</a> in terminal to make the install.</p> <p>Once that's done, you enter into the R console one more time</p> <pre><code>install.packages("RODBC") </code></pre> <ol start="3"> <li><p>Search <a href="https://dev.mysql.com/downloads/connector/odbc/" rel="nofollow noreferrer">MySQL for the appropriate ODBC installation</a>. I'm running Mac OSX 10.6 so I downloaded the dmg and installed it. This took care of itself.</p></li> <li><p>Now comes the tricky part. Apparently Mac OX took out the ODBC Administrator after a recent OS release, so you need to download ODBC Manager (<a href="http://www.odbcmanager.net/" rel="nofollow noreferrer">http://www.odbcmanager.net/</a>). It too is a dmg file so just drag and drop to your utilities folder.</p></li> </ol> <p>I had difficulties with the 5.3.6 dmg install (kept failing), so I installed 5.2.7 instead.</p> <ol start="5"> <li><p>Open ODBC Manager. You need to configure the DSN, so click the tab "System DSN" and click "add". </p></li> <li><p>You'll get a popup window asking you to select a driver. Mine had "MySQL ODBC 5.2 Driver" based on my MySQL ODBC install. Click "Ok". If you don't see the driver, then you need to confirm that the MySQL ODBC installed.</p></li> <li><p>In the next popup window, make the Data Source Name (DSN) whatever you want - but remember that this is the name you need to use to call from R. In the keyword area below (keywords will be in quotes and the value will be in parentheses), ADD</p> <p>"database" (with value of your database name)</p> <p>"server" (for the local environment do NOT use localhost - instead use the local IP address 127.0.0.1. *** This was the KEY piece for me)</p> <p>"uid" (database user ID)</p> <p>"pwd" (database password)</p> <p>"socket" (not sure if this was required, but after multiple tutorials it was left in my configuration and things work, so maybe you need it. You can find your socket location in my.cnf - do a spotlight search. The socket file location is under CLIENT)</p> <p>Here's what my configuration looked like:</p> <p>DSN ("test" - this was the at the top)</p> <p>database ("televisions")</p> <p>socket ("/Applications/XAMPP/xamppfiles/var/mysql.sock")</p> <p>uid ("root")</p> <p>pwd ("")</p> <p>server ("127.0.0.1")</p></li> <li><p>In R, execute below - I believe these last 3 steps need to be done every time you start R and before you make a MySQL query.</p> <p>library(RODBC)</p></li> <li><p>Make sure that you've turned on MySQL and Apache from the XAMPP control panel.</p></li> <li><p>Then execute</p> <p>odbcConnect("test") - notice how I used my DSN in the double quotes. Interchange as necessary.</p></li> </ol> <p>This should get you up and running. You can read other tutorials about making MySQL queries in R.</p> <p>I hacked this together from a lot of great posts on Stack Overflow (thanks everyone!), random other sites/email exchange histories, and the "R In A Nutshell" book by Joseph Adler, but let me know if I missed something or it's unclear.</p> <p>Good luck!</p>
34,579,890
0
<p>The wording is a bit confusing. The whole paragraph is talking about the case where no prototype has been declared for the function at the time it is called, so the section you highlighted is for the case where no prototype is declared when the function is called, but a prototype is used when the function is defined. Here is an example:</p> <pre><code>int main(int argc,char** argv) { f(3.0f); /* undefined behavior */ g(3.0); /* undefined behavior */ } int f(float v) { return v; } int g(double v,...) { return v; } </code></pre> <p>In this example, when <code>f</code> is called, no prototype has been declared, so <code>3.0f</code> is promoted to a <code>double</code>. However, the function is later defined with a prototype which takes a <code>float</code> instead of a <code>double</code>, so the behavior is undefined.</p> <p>Likewise for <code>g</code>, the behavior is undefined because the elipses are used in the prototype of the definition.</p>
18,886,564
0
<p>You can inspect the page to find out all the fields need to be posted. There is <a href="http://discover-devtools.codeschool.com/" rel="nofollow">a nice tutorial</a> for <code>Chrome DevTools</code>. Other tools like <code>FireBug</code> on FireFox or <code>DragonFly</code> on Opera also do the work while I recommend <code>DevTools</code>.</p> <p>After you post a query. In the <code>Network</code> panel, you can see the form data which actually been sent. In this case:</p> <pre><code>__EVENTTARGET: __EVENTARGUMENT: __LASTFOCUS: __VIEWSTATE:5UILUho/L3O0HOt9WrIfldHD4Ym6KBWkQYI1GgarbgHeAdzM9zyNbcH0PdP6xtKurlJKneju0/aAJxqKYjiIzo/7h7UhLrfsGul1Wq4T0+BroiT+Y4QVML66jsyaUNaM6KNOAK2CSzaphvSojEe1BV9JVGPYWIhvx0ddgfi7FXKIwdh682cgo4GHmilS7TWcbKxMoQvm9FgKY0NFp7HsggGvG/acqfGUJuw0KaYeWZy0pWKEy+Dntb4Y0TGwLqoJxFNQyOqvKVxnV1MJ0OZ4Nuxo5JHmkeknh4dpjJEwui01zK1WDuBHHsyOmE98t2YMQXXTcE7pnbbZaer2LSFNzCtrjzBmZT8xzCkKHYXI31BxPBEhALcSrbJ/QXeqA7Xrqn9UyCuTcN0Czy0ZRPd2wabNR3DgE+cCYF4KMGUjMUIP+No2nqCvsIAKmg8w6Il8OAEGJMAKA01MTMONKK4BH/OAzLMgH75AdGat2pvp1zHVG6wyA4SqumIH//TqJWFh5+MwNyZxN2zZQ5dBfs3b0hVhq0cL3tvumTfb4lr/xpL3rOvaRiatU+sQqgLUn0/RzeKNefjS3pCwUo8CTbTKaSW1IpWPgP/qmCsuIovXz82EkczLiwhEZsBp3SVdQMqtAVcYJzrcHs0x4jcTAWYZUejvtMXxolAnGLdl/0NJeMgz4WB9tTMeETMJAjKHp2YNhHtFS9/C1o+Hxyex32QxIRKHSBlJ37aisZLxYmxs69squmUlcsHheyI5YMfm0SnS0FwES5JqWGm2f5Bh+1G9fFWmGf2QeA6cX/hdiRTZ7VnuFGrdrJVdbteWwaYQuPdekms2YVapwuoNzkS/A+un14rix4bBULMdzij25BkXpDhm3atovNHzETdvz5FsXjKnPlno0gH7la/tkM8iOdQwqbeh7sG+/wKPqPmUk0Cl0kCHNvMCZhrcgQgpIOOgvI2Fp+PoB7mPdb80T2sTJLlV7Oe2ZqMWsYxphsHMXVlXXeju3kWfpY+Ed/D8VGWniE/eoBhhqyOC2+gaWA2tcOyiDPDCoovazwKGWz5B+FN1OTep5VgoHDqoAm2wk1C3o0zJ9a9IuYoATWI1yd2ffQvx6uvZQXcMvTIbhbVJL+ki4yNRLfVjVnPrpUMjafsnjIw2KLYnR0rio8DWIJhpSm13iDj/KSfAjfk4TMSA6HjhhEBXIDN/ShQAHyrKeFVsXhtH5TXSecY6dxU+Xwk7iNn2dhTILa6S/Gmm06bB4nx5Zw8XhYIEI/eucPOAN3HagCp7KaSdzZvrnjbshmP8hJPhnFhlXdJ+OSYDWuThFUypthTxb5NXH3yQk1+50SN872TtQsKwzhJvSIJExMbpucnVmd+V2c680TD4gIcqWVHLIP3+arrePtg0YQiVTa1TNzNXemDyZzTUBecPynkRnIs0dFLSrz8c6HbIGCrLleWyoB7xicUg39pW7KTsIqWh7P0yOiHgGeHqrN95cRAYcQTOhA== __SCROLLPOSITIONX:0 __SCROLLPOSITIONY:106 __VIEWSTATEENCRYPTED: __EVENTVALIDATION:g2V3UVCVCwSFKN2X8P+O2SsBNGyKX00cyeXvPVmP5dZSjIwZephKx8278dZoeJsa1CkMIloC0D51U0i4Ai0xD6TrYCpKluZSRSphPZQtAq17ivJrqP1QDoxPfOhFvrMiMQZZKOea7Gi/pLDHx42wy20UdyzLHJOAmV02MZ2fzami616O0NpOY8GQz1S5IhEKizo+NZPb87FgC5XSZdXCiqqoChoflvt1nfhtXFGmbOQgIP8ud9lQ94w3w2qwKJ3bqN5nRXVf5S53G7Lt+Du78nefwJfKK92BSgtJSCMJ/m39ykr7EuMDjauo2KHIp2N5IVzGPdSsiOZH86EBzmYbEw== ctl00$MainContent$hdnApplyMasterPageWitoutSidebar:0 ctl00$MainContent$hdn1:0 ctl00$MainContent$CorpSearch:rdoByEntityName ctl00$MainContent$txtEntityName:GO ctl00$MainContent$ddBeginsWithEntityName:M ctl00$MainContent$ddBeginsWithIndividual:B ctl00$MainContent$txtFirstName: ctl00$MainContent$txtMiddleName: ctl00$MainContent$txtLastName: ctl00$MainContent$txtIdentificationNumber: ctl00$MainContent$txtFilingNumber: ctl00$MainContent$ddRecordsPerPage:25 ctl00$MainContent$btnSearch:Search Corporations ctl00$MainContent$hdnW:1920 ctl00$MainContent$hdnH:1053 ctl00$MainContent$SearchControl$hdnRecordsPerPage: </code></pre> <p>What I post is <code>Begin with 'GO'</code>. This site is build with <code>WebForms</code>, so there are these long <code>__VIEWSTATE</code> and <code>__EVENTVALIDATION</code> fields. We need send them as well.</p> <p>Now we are ready to make the query. First we need to get a blank form. The following code are written in Python 3.3, through I think they should still work on 2.x.</p> <pre><code>import requests from lxml import etree URL = 'http://corp.sec.state.ma.us/CorpWeb/CorpSearch/CorpSearch.aspx' def get_fields(): res = requests.get(URL) if res.ok: page = etree.HTML(res.text) fields = page.xpath('//form[@id="Form1"]//input') return { e.attrib['name']: e.attrib.get('value', '') for e in fields } </code></pre> <p>With <code>get_fields()</code>, we fetched all <code>&lt;input&gt;</code>s from the form. Note there are also <code>&lt;select&gt;</code>s, I will just hardcode them.</p> <pre><code>def query(data): formdata = get_fields() formdata.update({ 'ctl00$MainContent$ddRecordsPerPage':'25', }) # Hardcode some &lt;select&gt; value formdata.update(data) res = requests.post(URL, formdata) if res.ok: page = etree.HTML(res.text) return page.xpath('//table[@id="MainContent_SearchControl_grdSearchResultsEntity"]//tr') </code></pre> <p>Now we have a generic <code>query</code> function, lets make a wrapper for specific ones.</p> <pre><code>def search_by_entity_name(entity_name, entity_search_type='B'): return query({ 'ctl00$MainContent$CorpSearch':'rdoByEntityName', 'ctl00$MainContent$txtEntityName': entity_name, 'ctl00$MainContent$ddBeginsWithEntityName': entity_search_type, }) </code></pre> <p>This specific example site use a group of <code>&lt;radio&gt;</code> to determine which fields to be used, so <code>'ctl00$MainContent$CorpSearch':'rdoByEntityName'</code> here is necessary. And you can make others like <code>search_by_individual_name</code> etc. by yourself.</p> <p>Sometimes, website need more information to verify the query. By then you could add some <a href="http://docs.python-requests.org/en/latest/user/quickstart/#custom-headers" rel="nofollow">custom headers</a> like <code>Origin</code>, <code>Referer</code>, <code>User-Agent</code> to mimic a browser.</p> <p>And if the website is using JavaScript to generate forms, you need more than <code>requests</code>. <a href="http://phantomjs.org" rel="nofollow"><code>PhantomJS</code></a> is a good tool to make browser scripts. If you want do this in Python, you can use <a href="http://www.riverbankcomputing.co.uk/software/pyqt/" rel="nofollow"><code>PyQt</code></a> with <code>qtwebkit</code>.</p> <p><strong>Update</strong>: It seems the website blocked our Python script to access it after yesterday. So we have to feign as a browser. As I mentioned above, we can add a custom header. Let's first add a <code>User-Agent</code> field to header see what happend.</p> <pre><code>res = requests.get(URL, headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36', }) </code></pre> <p>And now... <code>res.ok</code> returns <code>True</code>!</p> <p>So we just need to add this header in both call <code>res = requests.get(URL)</code> in <code>get_fields()</code> and <code>res = requests.post(URL, formdata)</code> in <code>query()</code>. Just in case, add <code>'Referer':URL</code> to the headers of the latter:</p> <pre><code>res = requests.post(URL, formdata, headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36', 'Referer':URL, }) </code></pre>
13,235,095
0
Centered table and margins are not working? <p>I have noticed that this forum I have written is fine in most browsers although in IE8 its to the left and not centered.</p> <p>Its CSS is <code>margin: auto auto</code>, which works in most browsers.</p> <p>I don't want to resort to going old fashioned and putting align="center" in the actual table properties.</p> <p>Can anyone explain it ?</p> <p><a href="http://forum.bestlincs.co.uk/" rel="nofollow">http://forum.bestlincs.co.uk/</a></p>
30,752,481
0
Different views with different code behinds but one binary in Windows 10 <p>I have been reading <a href="http://visuallylocated.com/post/2015/04/02/Creating-different-page-views-for-Windows-Apps-based-on-the-device.aspx" rel="nofollow">this</a> which suggests that in windows 10 you can use different xaml views (with the same code behind) for different device families. </p> <p>My question is whether you can use different views with different code behinds for different device families and still produce one binary. </p> <p>I know that I can use two head projects with one shared project and achieve the behavior I want but that would produce two binaries. </p> <p><strong>EDIT</strong>: To make the question a little bit more specific. Can I add a blank page(for example) <strong>with its code behind</strong>, to the DeviceFamily-Mobile folder and then use it, or must I use only "codebehindless" xaml files in that folder?</p>
20,061,078
0
Finding cache cpi time <p>I need a formula or to at least be pointed in the right direction it involves cache and cpi time. I have a base machine that has a 2.4ghz clock rate it has L1 and L2 cache. L1 is 256k direct mapped write through . 90% read without a hit rate without penalty, miss penalty costs 4 cycles all writes take 1 cycle. L2 cache is 2mb, 4 way set associative write back. 99.5% hit rate 60 cycle miss penalty. 30% of all instructions are reads and 10% are writes all other instructions take one cycle.. I need to figure how to get the cpi. I know i have to find the base cpi but from there I'm not really sure where to go. Any tips on not just what the answer is but how is more important would be greatly appreciated. </p>
19,855,766
0
<p>No, you can't do this. Everything you can do is add argument to command line to manage the heap size. </p> <p>A dirty solution can be to spawn another process with different heap size, but I don't think this is what you are looking for. <strong><a href="http://www.dreamincode.net/forums/topic/96263-how-to-set-heap-size/" rel="nofollow">Here</a></strong> there is an example.</p>
39,460,190
0
<p>When chaining observables you need to use <code>flatMap()</code>.</p> <pre><code>Observable.fromPromise(this.storage.get('accessToken')) .flatMap(accessToken =&gt; this.http.post('http://1234/user/login', {'accessToken': accessToken}) ) .subscribe( result =&gt; console.log(result), error =&gt; console.log(error) ); </code></pre> <p>A good explanation of this concept is found here - <a href="http://reactivex.io/documentation/operators/flatmap.html" rel="nofollow">http://reactivex.io/documentation/operators/flatmap.html</a></p>
20,144,030
0
<p>Currently there are 2 options for Git Source Control in Visual Studio (2010 and 12):</p> <ol> <li><a href="http://visualstudiogallery.msdn.microsoft.com/63a7e40d-4d71-4fbb-a23b-d262124b8f4c">Git Source Control Provider</a> </li> <li><a href="http://visualstudiogallery.msdn.microsoft.com/abafc7d6-dcaa-40f4-8a5e-d6724bdb980c">Microsoft Git Provider</a></li> </ol> <p>I have tried both and have found 1st one to be more mature, and has more features. For instance it plays nicely with both tortoise git and git extensions, and even exposed their features.</p> <p><strong>Note</strong>: Whichever extension you use, make sure that you enable it from <code>Tools -&gt; Options -&gt; Source control -&gt; Plugin Selection</code> for it to work.</p>
17,810,363
0
<p>The lambda solution would be the idomatic C++11 way:</p> <pre><code>auto a = [&amp;]( int x ){ return superComplexAlgorithm( 3, 4, 5, x ); }; for( unsigned int i = 0; i &lt; 100; ++i ) do_stuff_with( a ); </code></pre> <p>The advantage of using a hand written functor is that you can:</p> <ol> <li>Move arguments into the capture, or transform them (you can do that with lambda in C++1y, but not yet -- this is also possible with <code>bind</code>)</li> <li>It has a non-anonymous type (so you can talk about the type without using <code>auto</code>) -- the same is true of <code>bind</code>, but it also has a non-anonymous <em>meaningful</em> type you can get at without <code>decltype</code>ing the entire expression! C++1y again makes this better for <code>bind</code>/lambda.</li> <li>You can do perfect forwarding of the remaining arguments (you might be able to do this in C++1y with a lambda, and <code>bind</code> does this)</li> <li>You can mess around with how the captured data is stored (in a pointer? a smart pointer?) without messing up the code where you create the instance.</li> </ol> <p>You can also do some extremely powerful things with hand written functors that are impossible to do with <code>bind</code> and lambdas, like wrap an overload set of multiple functions into one object (that may or may not share a name), but that kind of corner case isn't going to show up often.</p>
40,169,916
0
iOS - presentViewController like the image (Open iMessages app store in Messages) <p><img src="https://i.stack.imgur.com/MZnz9m.jpg" alt="Open iMessages app store in Messages Screenshot"></p> <p>I want present a <code>UINavigationController</code> like the image above, I use</p> <pre><code>nvc.modalPresentationStyle = UIModalPresentationFormSheet; </code></pre> <p>But I can't change the controller's size.</p> <p>This is how I did:</p> <pre><code>UIViewController *vc = [[UIViewController alloc] init]; vc.view.backgroundColor = [UIColor grayColor]; UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc]; nvc.modalPresentationStyle = UIModalPresentationFormSheet; nvc.view.frame = CGRectInset(self.view.bounds, 20, 20); [self presentViewController:nvc animated:YES completion:nil]; </code></pre> <p>But the present viewController is still full screen.</p>
30,548,400
0
<p>Twitter's Tweet Web Intent doesn't provide this functionality. You'd have to build a solution using either the REST or Streaming APIs. Even that would only work if the user's Tweets are public, or if they give you read access to their timeline.</p>
23,930,126
0
How to find the Config File location via ConfigurationManager? <p>How to find the Config File location via ConfigurationManager?</p> <p>I have the ConfigurationManager class in code and I'm debugging it. I'd like to know to which config file it's pointing to (web.config or app.config, etc).</p> <p>Is there any property or method on the ConfigurationManager that can help with this?</p>
4,286,075
0
Brightness Screen Filter <p>Does anyone have an idea how to implement an Brightness Screen Filter like the one here:</p> <p><a href="http://www.appbrain.com/app/screen-filter/com.haxor">http://www.appbrain.com/app/screen-filter/com.haxor</a></p> <p>I need a starting point and I can't figure out how to do it.</p>
32,465,762
0
<p>I've found a solution. The problem was:</p> <pre><code> Intent intent = new Intent(myContext, myActivityClass); String s = stackTrace.toString(); //you can use this String to know what caused the exception and in which Activity intent.putExtra("uncaughtException", "Exception is: " + stackTrace.toString()); intent.putExtra("stacktrace", s); myContext.startActivity(intent); </code></pre> <p>Removing the startActivity, resolved the problem of the dialog, and still restarted the application as expected.</p> <p>EDIT:</p> <p>The dialog prompt but only because a second crashed occured because of missing data, so this answer is not correct...</p>
31,700,296
0
How to copy files with one extension to another extension <p>I have a.s b.s c.s d.s files in my current directory on my linux machine, I want to copy them to new extension .S like a.S b.S c.S d.S</p> <p>Please help me to do this.</p>
4,640,041
0
<p>You can somehow try to compress the information somehow. You need to show the user if he has read a post, only if the user logs on, so you should store the information somewhere near the user. The user might look throught your posts in a date sorted way, so read-post-information of nearly dates should ly nearby, for efficient caching and reading of many values.</p> <p>Try a table with this stucture:</p> <ul> <li>user_id</li> <li>postmonth</li> <li>readposts_array</li> </ul> <p>Depending on how many posts you expect, you might use week or day instead of month. If you cache the value in your app, you might see a performance increase when displaying many posts.</p>
33,746,828
0
<p>There's an old joke about two people at a natural history museum wondering how old a dinosaur fossil is. A guard overhears them and says, "Oh, it's five-hundred million and seven years old". One of the people says, "that's an astonshing number, how was it determined?" The guard says, "Well, I was told it was five-hundred million years old during my orientation, and that was seven years ago."</p> <p>This is the result of adding together two times with differing levels of precision. Say I start a clock at 12:03:06 and that clock only has minute resolution. If I add the time on my clock to the start time, I'll get a series of times like 12:03:06, 12:04:06, 12:05:06, and so on.</p> <p>Windows is adding the time from a monotonic clock with millisecond resolution and an arbitrary start time to the time at which that clock read zero with microsecond resolution.</p> <p>A common technique is simply to round the time to the resolution you are relying on, which of course must not be higher than the clock's guaranteed resolution. I believe the guaranteed resolution for this clock is 10 milliseconds.</p>
7,892,197
0
<p>How often these images change is not up to Amazon but depends entirely on the publishers.</p> <p>I work for a publishing house and I can tell you from personal experience that a book cover can change quite frequently before going into print. Once it's available as physical product though (i.e. no more pre-order), it will remain the same until the next edition is published.</p>
17,730,157
0
<p>To animate you'll need to define a starting state, and a target (or finished) state and an easing function to control the rate of change.</p> <p>Rather than start from scratch I'd suggest leveraging an existing solution, there is a LOT of code out there to help you do this.</p> <p>Check out: <a href="https://github.com/sole/tween.js" rel="nofollow">https://github.com/sole/tween.js</a></p>
38,831,165
0
<p>You could also download Unity Remote 4 for your Mobile phone. It really helped me a lot : <a href="http://docs.unity3d.com/Manual/UnityRemote4.html" rel="nofollow">http://docs.unity3d.com/Manual/UnityRemote4.html</a></p> <p><strong>edit</strong>:</p> <ol> <li>Download &amp; install Unity Remote 4 on your device.</li> <li>Enable USB debugging on your device and connect it to your pc.</li> <li>Start Unity Remote 4 and then restart Unity.</li> <li>In Unity, navigate to: Edit -> Project Settings -> Editor.</li> <li>In the Inspector, you can select now under "Unity remote' your device.</li> <li>Hit the Play Button in Unity.</li> </ol>
34,707,711
0
How do I get two things to hit each other and then remove one from the scene? <p>I have four colored bars aligned horizontally. I also have some of the exact colors falling from the top of the screen which need to be matched with the bars at the bottom and then removed from the scene on contact. (If falling yellow bar hits bottom yellow bar, remove falling yellow bar from the scene) So, should I have eight different cases for each node in an enum instead of four? This is what it looks like now:</p> <pre><code>enum Bodies: UInt32 { case blueBar = 1 case redBar = 2 case yellowBar = 4 case greenBar = 8 } </code></pre> <p>Some of them are not doing what they're supposed to which is why I'm asking. Thanks in advance. </p>
15,935,282
0
breadth first search trouble [solved it] <p>Working on a breadth first search but cant seem to get it to work. The bfs is searching through an array of linked lists (an adjacency matrix). I followed the algorithm in my text book as well as looked over a few on the internet, but i think since that I am using an array of linked lists it's having trouble vs the standard of using a graph. Could anyone please help me resolve where the issues are occurring?</p> <p>This is my BFS method:</p> <pre><code>public static int bfs(List&lt;Integer&gt;[] smallWorld, int start){ int distance = 0; int size = smallWorld.length; //for each location in smallWorld do a bfs to every other location int u; int white = 0, grey = 1, black = 2; int [] color, d, pie; Queue &lt;Integer&gt; q = new &lt;Integer&gt; LinkedList(); color = new int [size]; d = new int [size]; pie = new int [size]; for( int x = 0; x &lt; size; x++){ //for all indexes in the smallWorld array color[x] = white; //color them white d[x] = -1; //make the distance array @ each index infinity (-1) pie[x] = -1; //make the pie array @ each index null (-1) } color[start] = grey; //At the starting / current index color it grey d[start] = 0; //the distance @ starting array is 0 obviously pie[start] = -1; //make pie array @ current index / starting index null (-1) q.addAll(smallWorld[start]); //enqueue the items adjacent to current index while(!q.isEmpty()){ //while the queue is not empty u = q.remove(); //dequeue the first item and set it to u for(int v = 0; v &lt; smallWorld[u].size(); v++){ //for every vertex u is adjacent to if(color[smallWorld[u].get(v)] == white){ //if the color is white of that adjacent vertex color[smallWorld[u].get(v)] = grey; //color it grey d[v] = d[u] + 1; //make the distance pie[v] = u; q.addAll(smallWorld[v]); } } color[u] = black; } int x = 0; while(d[x] != -1){ distance = distance + d[x]; x++; } return distance; } </code></pre> <p>I just dont see why the algorithm isn't working and I'm pretty sure I adjusted it to work with array of <code>LinkedList</code>s.</p>
25,357,876
0
Replacing double quotes while sending parameter to javascript function <p>This is JSFiddle :</p> <p><a href="http://jsfiddle.net/5kdek3vn/" rel="nofollow">http://jsfiddle.net/5kdek3vn/</a> </p> <p>I have button as follows:</p> <pre><code>&lt;button class="buttoncss" title="Modify This Artifact File" onclick="setFileDescriptionForUpdate('!@#$%^&amp;amp;*()_+-=~`{}|[]\:" ;'&amp;lt;&amp;gt;?,.="" ','state.dat','167','1','c:\\pp_artifactsuploadedfiles\evalid_318\state.dat');"&gt;Modify&lt;/button&gt; </code></pre> <p>in this on click i am calling <code>setFileDescriptionForUpdate</code> function whose first parameter is string and is as follows:</p> <pre><code>!@#$%^&amp;*()_+-=~`{}|[]\:";'&lt;&gt;?,./ </code></pre> <p>when " is involved in string it creates problem.</p> <p>What changes i can make to avoid this??</p> <p>Please help me.</p>
12,863,141
0
<p>Do it programmatically at runtime? (In your <code>-applicationDidFinishLaunching:</code> delegate method)</p>
12,561,289
0
<p>you should use <a href="http://regexkit.sourceforge.net" rel="nofollow">Regexkit Framework</a>, i found it the best solution for regex in iOS</p>
5,480,611
0
<p>Just took a look, and its actually Adobe who owns it, and they sell it for money. So, my <em>best</em> guess is no, you couldn't legally use it for free. I have no idea if Adobe licenses it, though. Maybe you could try and find one that's licensed for web use, and is similar to Helvetica?</p>
17,622,590
0
<p><em>I've moved the most important points from the comments.</em></p> <ol> <li><p>Yep, that's the normal behavior. Nginx's master process needs root privileges to manage listening sockets on the machine. <a href="http://forum.nginx.org/read.php?2,159000,159015#msg-159015" rel="nofollow">This</a> forum thread states that you <strong>can</strong> change it, but it may cause problems. However, Nginx does allow to change the owner of the worker processes.</p></li> <li><p>It depends on how the uWSGI was installed. If uWSGI was installed via <code>apt-get</code> you can start (stop, restart) it like this:</p> <p><code>service uwsgi &lt;action&gt;</code></p> <p>You installed uWSGI via <code>pip</code>, so the <a href="https://uwsgi-docs.readthedocs.org/en/latest/Options.html#daemonize" rel="nofollow">daemonize</a> option will do the trick:</p> <p><code>/path/to/uwsgi --daemonize /path/to/logfile</code></p> <p>You can start it under any user you want, BUT if you decide to run it under root, you should specify the <a href="https://uwsgi-docs.readthedocs.org/en/latest/Options.html#gid" rel="nofollow">gid</a> and <a href="https://uwsgi-docs.readthedocs.org/en/latest/Options.html#uid" rel="nofollow">uid</a> options. uWSGI's <a href="https://uwsgi-docs.readthedocs.org/en/latest/ThingsToKnow.html" rel="nofollow">best practices page</a> says:</p> <blockquote> <p>Common sense: do not run uWSGI instances as root. You can start your uWSGIs as root, but be sure to drop privileges with the uid and gid options.</p> </blockquote> <p>Also take a look at <a href="https://uwsgi-docs.readthedocs.org/en/latest/Options.html?highlight=uid#master-as-root" rel="nofollow">master-as-root</a> option.</p></li> <li><p>You can create as many processes and threads as you want, but it should depend on how many requests you're trying to process (concurrent or per second). You can read about this <a href="https://uwsgi-docs.readthedocs.org/en/latest/ThingsToKnow.html" rel="nofollow">here</a>. I would try different configurations and choose which one works better.</p> <p>3b. Basically, <code>worker_processes</code> helps to handle concurrent requests. See <a href="http://stackoverflow.com/questions/7325211/tuning-nginx-worker-process-to-obtain-100k-hits-per-min">this</a> question.</p></li> <li><p><em>*WARNING: you are running uWSGI without its master process manager*</em></p> <p>You didn't specify a <code>master</code> option in your .ini file. While master process is certainly unnecessary, it is very useful. It helps to effectively control workers and respawn them when they die.</p></li> </ol>
31,617,310
0
Check if there are more than 1 argument <p>I have a simple program that encrypts message using <code>Caesar Cipher</code>.</p> <p>The program works well, but I am unable to check whether the user is entering more than 1 argument. If he is, I need to break and prompt the user to enter the correct number of arguments which is <code>1</code>.</p> <p>If you enter more than 1 argument in terminal, say <code>./caesar 13 56 hello</code> it will still work but it shouldn't</p> <pre><code>int main(int argc, string argv[]) { int indexKey = 0; string message; if (argc &lt; 2 || atoi(argv[0]) &lt; 0 || atoi(argv[1]) &lt; 0) { printf("Please enter a non-negative integer as an argument.\n"); return 1; } else { indexKey = atoi(argv[1]); } </code></pre> <p>How do I prevent the user from entering too many arguments?</p>
4,246,473
0
<p>50 decimal is 32 hexadecimal.</p> <p>Apart from that, the <a href="http://www.cplusplus.com/reference/clibrary/cstdio/printf/" rel="nofollow">documentation</a> should tell you all you need to know.</p>
34,727,887
0
<p>Fixed it using some of the suggestions below.</p> <pre><code>$startDate = new DateTime(date("2012-4-1")); $endDate = new DateTime(date("Y-m-t", strtotime($startDate-&gt;format("Y-m-d")))); echo "The start date should be 2012-4-1: " . $startDate-&gt;format("Y-m-d") . "&lt;br /&gt;"; echo "The end date should be 2012-4-30: " . $endDate-&gt;format("Y-m-d") . "&lt;br /&gt;"; </code></pre> <p>I've verified that this works.</p>
5,447,072
0
<p>The equality operator will attempt to make the data types the same before making the comparison. On the other hand, the identity operator requires both data types to be the same as a prerequisite.</p> <p>There are quite a few other posts out there similar to this questions. See:</p> <p><a href="http://stackoverflow.com/questions/80646/how-do-the-equality-double-equals-and-identity-triple-equals-compariso">How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?</a> (has a nice comparison chart)<br /> <a href="http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use">Does it matter which equals operator (== vs ===) I use in JavaScript comparisons?</a></p> <p>In practice, the identity operator comes in really handy when you want to be certain that a boolean value is true or false since...</p> <pre><code>1 == true =&gt; true true == true =&gt; true 1 === true =&gt; false true === true =&gt; true </code></pre>
4,639,592
0
<p>If you wanted to go down the route of iteratively testing each public method in the controller, you could do something like:</p> <pre><code>SomeController.public_instance_methods(false).each do |method| it "should do something" end </code></pre> <p>However, I think a shared example group (see about half way down this page: <a href="http://rspec.info/documentation/" rel="nofollow">http://rspec.info/documentation/</a>) would be prettier. If it were extracted so it could be used across all your controller specs, it'll be even nicer..</p> <pre><code>shared_examples_for "admin actions" do it "should require login" end </code></pre> <p>Then in each controller spec:</p> <pre><code>describe SomeController do it_should_behave_like "admin actions" end </code></pre>
20,214,430
0
SSRS Date Parameter Not working <p>I have two parameters for the report "StartDate" and "EndDate" respectively. They work fine in the chart filter expressions , however when I use the same in the series expression as CDate(Parameters!Startdate.Value) > CDate(Fields!InAck.value) of the chart to compare against a date column in the dataset and calculate the series value for datediff, it doesn't return the values promptly .</p>
37,695,583
0
Sorting conversations with belongs_to/has_many relationship <p>i have the following models:</p> <pre><code>class Post &lt; ActiveRecord::Base has_many :conversations end class Conversation &lt; ActiveRecord::Base belongs_to :user belongs_to :post has_many :messages end class Message &lt; ActiveRecord::Base belongs_to :conversation end </code></pre> <p>So there are Posts, and each post can have many conversations. In each conversation are many messages. So far so good.</p> <p>Now i wanna display an overview of all conversations a user has. It seems i can't get it to work the way i want:</p> <p>Get all conversations the current user has (<code>current_user.conversations</code>) group all conversations according to the Post ID they <code>belong_to</code> and rank this groups by date -> The group (of conversations) with the newest message should appear on top. Here is a screenshot of what i have so far. <a href="https://i.stack.imgur.com/SCOaM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SCOaM.png" alt="Sorting conversations"></a></p> <p>All covnerations should be grouped by Posts they belong to at every times. If any conversation has a new message in it, the whole group of conversations should move to the top of the view, not only the conversation with the new message. That's what i can't get to work.</p> <p>The screenshot above was made with the following code:</p> <pre><code>current_user.conversations.includes(:messages, post: :user).order("posts.id DESC, messages.created_at DESC").to_a.paginate( :page =&gt; params[:page], :per_page =&gt; 10 ) </code></pre> <p>As you can see in the screenshot, the conversations are grouped by their post id. But the second group should appear above the first group, because the conversation in the second group has the latest message in it.</p> <p>Any help is appreciated. Thanks a lot!</p>
38,853,562
0
Viewpager snaps to the wrong page after taking a photo <p>I am currently using a <strong>Viewpager</strong> implementation in my android app. In each of the fragment, there is a <strong>button</strong> that takes a photo and uploads it to an online database. However, due to the new permissions requirement, I needed to ask for permission. Hence, i would need to use the <strong><em>onRequestPermissionsResult()</em></strong> to continue uploading.</p> <p>Below is my implementation</p> <p>this is from the <strong>ViewPager.class</strong> (Since after permission is granted, this method in the Viewpager is called instead of the one in the fragment)</p> <pre><code>@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_TAKE_PHOTO: if (grantResults.length &gt; 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) { //Permission granted to write and read file //Get the current fragment List&lt;Fragment&gt; fragments = getSupportFragmentManager().getFragments(); for (Fragment currFragment : fragments) { if (currFragment != null) currFragment.onRequestPermissionsResult( REQUEST_TAKE_PHOTO , permissions , grantResults); } } return; default: //Do nothing return; } } </code></pre> <p>this is from the <strong>fragment</strong> itself</p> <pre><code>@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_TAKE_PHOTO: if (grantResults.length &gt; 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) { //Permission granted to write and read file uploadImage(); } return; default: //Do nothing return; } } </code></pre> <p>this part</p> <pre><code>List&lt;Fragment&gt; fragments = getSupportFragmentManager().getFragments(); for (Fragment currFragment : fragments) { if (currFragment != null) currFragment.onRequestPermissionsResult( REQUEST_TAKE_PHOTO , permissions , grantResults); } </code></pre> <p>is my attempt to find the <strong>correct fragment</strong> that clicked the button and call the <strong>OnRequestPermissionResult()</strong> method.</p> <p>However, I notice this weird behavior from <strong>Viewpager</strong>. The way I implemented it is that I click a <strong>Viewholder</strong> from a <strong>RecyclerView</strong>, then that enters that position in the ViewPager.</p> <p>The weird behavior is that for example, I entered page 2 from the <strong>RecyclerView</strong>. Then i swipe to page 4 and click the upload photo button, after the photo is done(via the in-build camera app), it will switch back to page 2.</p> <p>Why is that? How do I fix it? Sorry for a lengthy post. Just trying to get as much information out there. Thanks</p> <p>EDIT: This is how I call the requestPermission</p> <pre><code>@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != Activity.RESULT_OK) { return; } if (requestCode == REQUEST_TAKE_PHOTO) { //Request for permission to access file if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //ask for permission ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_TAKE_PHOTO); } else { uploadImage(); } } } </code></pre> <p>Is something wrong?</p> <p>Edit Post: This is the part where I called the notifyDataSetChange()</p> <pre><code>private void loadData() { mRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { ArrayList&lt;RouteInstructions&gt; mList2 = new ArrayList&lt;RouteInstructions&gt;(); for (DataSnapshot instructions : dataSnapshot.getChildren()) { mList2.add(instructions.getValue(RouteInstructions.class)); } mList = mList2; mAdapter.notifyDataSetChanged(); mPager.setCurrentItem(getIntent().getIntExtra(EXTRA_INDEX, 0)); } @Override public void onCancelled(DatabaseError databaseError) { } }); } </code></pre>
27,476,257
0
Trouble with layer(geom="line") in ggplot <p>I would like to plot a line chart in ggplot2. Here is how my data look like</p> <pre><code>query,trace,precision,recall safe.order.q3.txt,rstr_oper_50000_100m,49.8406,24.9156 safe.order.q3.txt,sstr_cpu_50000_100m,49.774,24.8442 safe.order.q3.txt,sstr_oper_50000_100m,49.8735,24.885 safe.sem.q1.txt,ran_50000_100m,74.9204,24.8125 safe.sem.q1.txt,sys_50000_100m,58.1995,11.8975 safe.sem.q1.txt,rstr_cpu_50000_100m,75.6115,25.1855 safe.sem.q1.txt,rstr_oper_50000_100m,75.2262,24.9382 safe.sem.q1.txt,sstr_cpu_50000_100m,74.997,25.0963 safe.sem.q1.txt,sstr_oper_50000_100m,75.4195,25.3233 safe.sem.q2.txt,ran_50000_100m,78.6449,24.6323 safe.sem.q2.txt,sys_50000_100m,10.9353,0.255188 safe.sem.q2.txt,rstr_cpu_50000_100m,79.3762,24.6961 </code></pre> <p>And here is the ggplot code that I store in the file <code>recprec.r</code></p> <pre><code>w &lt;- read.csv(file="../queryResults/comparison.100m.dat", head=TRUE, sep=",") sem1 &lt;- subset(w, query=="safe.sem.q1.txt") p1 &lt;- ggplot(data=sem1, aes(x=trace, y=precision)) + layer(geom="line") + geom_text(aes(y=precision + .4, label=precision)) print(p1) </code></pre> <p>The execution of the code produce the following error and the char depicted in the image below where lines between values are not displayed</p> <pre><code>&gt; source("recprec.r") geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic? </code></pre> <p><img src="https://i.stack.imgur.com/UEvUi.png" alt="enter image description here"></p> <p>What did I missed ?</p>
1,772,088
0
<p>I often add collection-based update_multiple and destroy_multiple actions to an otherwise RESTful controller.</p> <p>Check out this <a href="http://railscasts.com/episodes/52-update-through-checkboxes" rel="nofollow noreferrer">Railscast</a> on Updating Through Checkboxes. It should give you a good idea how to approach it, come back and add to this question if you run into troubles!</p>
23,935,035
0
<p>You can use following doc type. However I find some discrepancy in the code you have copied. Are you sure of INSERT and SELECT statements. I hope its copy mistake</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"&gt; &lt;mapper namespace="com.javacodegeeks.snippets.enterprise.UserMapper"&gt; &lt;select id="addUser" parameterType="int" resultType="com.javacodegeeks.snippets.enterprise.User"&gt; insert into * from users where id = #{id} &lt;/select&gt; &lt;select id="getUser" parameterType="int" resultType="com.javacodegeeks.snippets.enterprise.User"&gt; select * from com.javacodegeeks.snippets.enterprise.User where id = #{id} &lt;/select&gt; &lt;/mapper&gt; </code></pre>
23,093,328
0
Can Visual Studio 2013 show mixins from referenced files <p>When I hover over a mixin it shows me the properties, which is awesome!</p> <p>However, I have many referenced files and it does not show those. It says, "Undeclared mixin". Seems this would be a standard feature considering that many break up styles into like sections (reset, grid, fonts, etc.).</p> <p>thanks.</p>
32,415,813
0
<p>As Luksprog mentioned in the comment, ListAdapter is not filterable, you would have either have to create a customAdapter by extending the listadapter and implementing filterable in that object, or use an adapter provided by the sdk that implementals filterable</p>
6,742,928
0
<p>Here are a few links that you might find interesting. There is an example of creating a two-activity application, and then implementing fragments into it. </p> <p><a href="http://mobile.tutsplus.com/tutorials/android/android-sdk_fragments/">Android User Interface Design: Working With Fragments</a></p> <p><a href="http://mobile.tutsplus.com/tutorials/android/android-compatibility-working-with-fragments/">Android Compatibility: Working with Fragments</a></p> <p>Hope this helps.</p>
23,457,152
0
Will calling window.setInterval open a new thread in chrome? <p>I've read that all browsers except chrome have javascript code running in a single thread. I'm not even sure if this is still true, but assuming it is: Will calling window.setInterval multiple times open multiple threads in chrome?</p>
13,727,776
0
Sampling HBase table keyspace <p>I'd like to build random samples of a HBase table's rowkey space.</p> <p>Say, I'd like to have roughly 1% of the keys from HBase that are randomly distributed across the table. What's the best way of doing this?</p> <p>I suppose I could write a MapReduce job that processed all the data and pulled 1/100 of the keys... or perhaps use a coprocessor.</p>
17,706,796
0
recording uplink and downlink separately in different file at once <p>Have anyone tried saving uplink and downlink separately at once in different file? Or saving uplink and uplink+both side in different file.</p> <p>I found that in a different post that it might be possible using thread because recording channel stays busy. Anyone succeed to do that? Please give me some workable source if possible. </p> <p>Is it possible at all or not?</p>
36,819,186
0
Cloud Foundry compatibility with DBs <p>I have a set of restful services connecting to Oracle , MySQL and Phoenix DBs. These are running on tomcat. I have to migrate these services to pivotal cloud foundry. Is it sufficient if I externalize the connection parameters potentially using cloud config server or env variables to connect to these databases or is there anything additional that I need to do? I assume any db which works with a java application deployed outside cloud foundry will work when the app is deployed to pivotal cloud foundry. Please correct me if my assumption is incorrect.</p>